我正在为java类创建一个员工时钟。我的程序的这一部分需要在接受“打卡时间”之前检查是否存在“打卡时间”。
当我只使用if
循环时,该部分似乎有效。当我添加else
时,它会忽略if
并执行else
。
我能否就更好的方法获得一些反馈?
public static void punchIn() throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Date and time (format MM/dd/yyyy HH:mm:ss): ");
String timeentry = sc.nextLine();
System.out.print("Enter the employee ID number: ");
String idnumber = sc.nextLine() + " ";
String inorout = "in";
System.out.println("The Punch-in date / time is: " + timeentry);
System.out.println("The employee ID number is: " + idnumber);
System.out.println("The employee is punched-" + inorout);
PunchinPunchoutData product = new PunchinPunchoutData();
product.setTimeentry(timeentry);
product.setIdnumber(idnumber);
product.setInorout(inorout);
productDAO.punchIn(product);
System.out.println();
System.out.print("Press enter to continue ");
sc.nextLine();
}
public static void punchOut() throws FileNotFoundException, IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Date and time (format MM/dd/yyyy HH:mm:ss): ");
String timeentry = sc.nextLine();
br = new BufferedReader(new FileReader("timeclock1.txt"));
String line = "";
System.out.print("Enter an employee ID number: ");
String idnumber = sc.next() + " ";//read the choice
sc.nextLine();// discard any other data entered on the line
while ((line = br.readLine()) != null) {
if (line.contains(idnumber + " ") && line.endsWith("in")) {
break;
}
else {
System.out.println("There is no punch-in record for ID number:
" + idnumber);
System.out.println("A punch-in entry must be saved first");
punchIn();
break;
}
}
String inorout = "out";
System.out.println("The Punch-out date / time is: " + timeentry);
System.out.println("The employee ID number is: " + idnumber);
System.out.println("The employee is punched-" + inorout + ".");
PunchinPunchoutData product = new PunchinPunchoutData();
product.setTimeentry(timeentry);
product.setIdnumber(idnumber);
product.setInorout(inorout);
productDAO.punchOut(product);
System.out.println();
System.out.print("Press enter to continue ");
sc.nextLine();
}
答案 0 :(得分:0)
您似乎正在逐行阅读文件,以检查员工是否有"打入"记录。在您的代码中,当您拥有一条不属于该员工的行时,您正在调用punchIn
,这很可能会添加一个" punch-in"每次调用punchOut
时。您应该遍历整个文件,并且只有当文件中没有行包含记录时才调用punchIn
。
boolean foundPunchIn = false;
while ((line = br.readLine()) != null) {
if (line.contains(idnumber + " ") && line.endsWith("in")) {
foundPunchIn = true;
break;
}
}
if(!foundPunchIn) {
System.out.println("There is no punch-in record for ID number: " + idnumber);
System.out.println("A punch-in entry must be saved first");
punchIn();
}
String inorout = "out";
...