繁体   English   中英

Java:如何将用户输入与文本文件中的列进行比较?

[英]Java: How do I compare user input to columns in text file?

我对Java还是很陌生,因此经过几天的尝试来弄清楚如何将用户输入与文本文件中的列进行比较之后,我迫切需要帮助。 我想确保打孔的员工之前没有打过孔,之后又没有打过孔。 另外,我希望能够确保用户除非事先进行过打入,否则无法对系统进行打出。 我知道我必须对文本文件中的行进行分割,以使其分别可访问,但是我不知道如何将它们与用户输入进行比较。 任何帮助是极大的赞赏! 我的代码如下:

    import java.text.*;
    import java.util.*;
    import java.io.*;
    import java.nio.file.*;  

public class TimeClockApp
    {
    // declare class variables
    private static EmployeeDAO employeeDAO = null;
    private static TimeClockDAO timeClockDAO = null;
    private static Scanner sc = null;
    // format date and time / //HH converts hour in 24 hours format (0-23), day calculation
    private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

public static void main(String[] args) throws Exception
{
    // set the class variables
    employeeDAO = DAOFactory.getEmployeeDAO();
    timeClockDAO = DAOFactory.getTimeClockDAO();
    sc = new Scanner(System.in);
    int employeeID = 0;

    List<Employee> employees = employeeDAO.readEmployees();
    List<TimeClock> timePunches = timeClockDAO.readTimePunches();
    if(timePunches == null)
    {
        timePunches = new ArrayList<TimeClock>();
    }

    // display a welcome message
    System.out.println("Welcome to the Punch-In/Punch-Out Screen\n");

    // print option menu
    System.out.print("Please choose an option below:" + "\n"
           + "I. Punch In" + "\n"
           + "O. Punch Out" + "\n");

    String choice = "";
    // get input from user
    Scanner sc = new Scanner(System.in);

    while(choice != null)
    {
        // get input from user "i" or "o"
        while (!choice.equalsIgnoreCase("i") && !choice.equalsIgnoreCase("o"))
        {
            // it will not continue if user does not enter a valid choice
            choice = Validator.getScreenChoice(sc, "Choice: ");
            if(!choice.equalsIgnoreCase("i") && !choice.equalsIgnoreCase("o"))
            {
                System.out.println("Invalid choice.  Please try again.");
            }
        }
        System.out.println(); // print a blank line

        if(!choice.isEmpty())
        {
            // create employee object
            Employee employee = null;

            System.out.println("PUNCH CLOCK");
            System.out.println("-----------");

            // read employee ID and compare to employee.txt
            while(employee == null)
            {
                employeeID = Validator.getEmployeeID(sc,
                        "Enter Employee ID:    ");

                for(Employee e : employees)
                {
                    if(e.getEmployeeID() == employeeID)
                    {
                        employee = e;
                        break;
                    }
                }
            }
            // if employee ID is valid, have they punched in already?
            // if not, try again.

            // read timeclock.txt
           timeClockDAO.readTimePunches();

            if(employeeID == employee.getEmployeeID() && choice.equalsIgnoreCase("o")) // <-- This is where I'm having trouble
            {

               if(timePunches.contains("i"))
                {
                    if(timePunches.contains(employeeID))
                    {
                        System.out.println("Employee " + employeeID + " has already punched in. Please try again.");
                    }
                }

                // has employee punched in?  If yes, continue. <-- Beginning here, NetBeans ignores this whole deal
                for(TimeClock t : timePunches)
                {
                    if(t.getPunchInOrOut() && choice.equalsIgnoreCase("i"))
                    {
                        timePunches = t;
                        break;
                    }
                }
               // if employee has not punched in, try again
               if(timePunches.contains("i"))
                {
                    if(timePunches.contains(employeeID))
                    {
                        System.out.println("Employee " + employeeID + " has not punched in yet. Please try again.");
                    }
                }
            } // <-- NetBeans stops ignoring and continues from here

            TimeClock newTimePunch = new TimeClock(employeeID, new Date(), choice);

            // if employee ID is valid,
            // addition of date and time to arraylist/text file
            timePunches.add(newTimePunch);

            //write to the file
            timeClockDAO.writeTimePunch(newTimePunch);

            // conditional statement for in/out + formatting
            System.out.println("Punch-" + (choice.equalsIgnoreCase("i") ? "In" : "Out") + " Successful!" + "\n"
                             + "Date & Time:   " + dateFormat.format(new Date()) + "\n"
                             + "Employee Name: " + employee.getFirstName() + " " + employee.getLastName() + "\n"
                             + "Employee ID:   " + employee.getEmployeeID() + "\n");

            System.out.println(); // print a blank line
            break;
        }
        else
        {
            System.out.println("Invalid entry. Please try again.");
        }
    }

    // press enter to continue to the main screen
    System.out.printf("Press enter to return to the main screen. ");
    sc.nextLine();
    System.out.println("Okay, returning to Main Screen.  Goodbye!");
    System.out.println(); // print a blank line

    MainScreenApp.main(args);
}

}

我可以使用代码的timeClockDAO.readTimePunches()部分读取文本文件中的列并将其与用户输入进行比较,因为这些列已经被拆分了? List<TimeClock> timePunches()列表中的timeClockDAO.readTimePunches()方法如下:

        @Override
public List<TimeClock> readTimePunches()
{
    if(timePunches != null)
        return timePunches;

    timePunches = new ArrayList<TimeClock>();
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    if(Files.exists(Paths.get(timeClockPath))) // prevent the FileNotFoundException
    {
        try(BufferedReader in = new BufferedReader(
                                new FileReader(
                                new File(timeClockPath))))
        {
            // read all employees in the file into the array list
            String line = in.readLine();
            while(line != null)
            {
                // split text file into columns
                String[] columns = line.split(EmployeeTextFile.FIELD_SEP);
                /*if(columns.length != 3)
                {
                    System.err.println("Could not read text file for Time Punches.");
                    return null;
                }*/
                // employee ID column
                int employeeID = Integer.parseInt(columns[0]);
                // time stamp column
                Date timeStamp;
                try
                {
                    timeStamp = dateFormat.parse(columns[1]);
                }
                catch (ParseException e)
                {
                    System.err.println("Could not parse time stamp: " + columns[1]);
                    timeStamp = null;
                }
                // in or out column
                String punchInOrOut = columns[2];
                timePunches.add(new TimeClock(employeeID, timeStamp, punchInOrOut));

                line = in.readLine();
            }
        }
        catch(IOException e)
        {
            System.out.println(e);
            return null;
        }
    }
    return timePunches;
}

先感谢您!

由于timePunchesTimeClock的arrayList,因此if(timePunches.contains("i"))if(timePunches.contains(employeeID))行将不起作用,除非您使用比较器或实现Comparable接口,否则无法检查它包含一个String值或一个Employee值。

正如我在您的代码中所假设的那样,您将timePunches添加到文件的末尾,因此您只需要与ArrayList的最后一项进行比较,以查看当前员工的状态是否被打入或打出。

代替if(timePunches.contains("i"))if(timePunches.contains(employeeID))您应该首先仅使用当前的Employee打孔填充ArrayList。 然后,执行类似的操作:

if((timePunches.get(timePunches.size()).getPunchedInOrOut.equals("i") && choice.equals("o")) || (timePunches.get(timePunches.size()).getPunchedInOrOut.equals("o") && choice.equals("i")) ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM