我有一些代码需要在成功验证后中断,但我不知道在哪里添加它。我已经尝试在循环之后添加它并且接受成功的身份验证但似乎无法使其正常工作。
另一个小问题是在这一行;
System.out.println("..." + i);
表示它不在主要方法中,因为此代码是在工作中的PC上编写的,后来又添加到我的原始代码中。
这是我的代码;
public class Elevator {
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
final int UserID = 5555;
final int Password = 1234;
final int StudentNumber = 22334455;
int EnteredUserID;
int EnteredPassword;
int EnteredStudentNumber;
for (int s = 0; s <= 3; s++) {
if (s < 3) {
System.out.println("Enter your UserID to access lift;");
EnteredUserID = console.nextInt();
System.out.println("Your UserID is ==> " + EnteredUserID);
System.out.println("Enter your password to authenticate login;");
EnteredPassword = console.nextInt();
System.out.println("Password Entered is ==> " + EnteredPassword);
System.out.println("Enter your student number to finalise login and authentication;");
EnteredStudentNumber = console.nextInt();
System.out.println("Student Number Entered is ==> " + EnteredStudentNumber);
if (UserID == EnteredUserID && (Password == EnteredPassword)
&& (StudentNumber == EnteredStudentNumber)) {
System.out.println("Athentication complete!");
System.out.println("***Elevator access granted!***");
System.out.println("Welcome...");
//Break goes here?
} else {
System.out.println("Wrong UserID, Password or Student Number. Please try again.");
}
} else {
System.out.println("3 incorrect enteries detected. Access Denied!");
}
}
}
private int currentFloor;
public Elevator() {
currentFloor = 0;
}
public void selectFloor() {
Scanner scnr = new Scanner(System.in);
int newFloor;
System.out.println("Enter your destination floor ==> ");
newFloor = scnr.nextInt();
if (newFloor > 7 || newFloor < 0) {
System.out.println("Invalid floor entry");
}
else {
int direction = 0;
if(currentFloor < newFloor){
direction = 1;
} else if (currentFloor > newFloor) {
direction = -1; ;
} else {
direction = 0;
}
for (; currentFloor != newFloor; currentFloor += newFloor)
System.out.println("..." + i);
System.out.println("Elevator has arrived!");
}
}
public void fireAlarm() {
System.out.println("***FIRE ALARM*** Please exit the building safely.");
}
}
修改
所以我将break;
添加到我的代码中,我希望它在声明i
之后似乎只能起作用,而是将其更改为currentFloor
。身份验证系统工作正常,但是我的代码的下一部分似乎在成功验证后没有运行。我没有给出任何错误,代码根本没有运行。我有一种与支架放置有关的感觉,但我无法弄清问题是什么。
答案 0 :(得分:0)
break
关键字将退出循环,因此我认为您需要的是continue
。
continue
将仅中断循环中的当前进程并开始下一个循环操作。
并为此:
System.out.println("..." + i);
您尚未在i
方法搜索中声明setFloor
变量。
答案 1 :(得分:0)
你可以这样试试:
public static void main(String[] args) {
boolean succeeded = false;
for (int tries = 1; tries <= 3; tries++) {
succeeded = authenticateUser();
if (succeeded) break;
// do the please try again stuff
}
if (succeded) {
// do the print to console stuff
} else {
// do the sorry to many failed attempts stuff
}
}
private static boolean authenticateUser() {
boolean isSuccess = false;
// do the authentication stuff
// set isSuccess if authentication succeeded
return isSuccess;
}