我为电梯创建了一个登录系统,需要当前正常工作的身份验证。我遇到的问题是程序在成功登录后无法继续运行。登录失败将在3次尝试失败后终止程序;这也行得很好。我认为它与我的break;
行或我的括号位置有关。我尝试过使用continue;
,但这也不起作用。代码的下一部分在登录后不会运行,也没有给出错误。
这是我的代码;
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;
} 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("..." + currentFloor);
System.out.println("Elevator has arrived!");
}
}
public void fireAlarm() {
System.out.println("***FIRE ALARM*** Please exit the building safely.");
}
}
我可能遗漏了一些非常简单的东西,但似乎无法找到它。
答案 0 :(得分:2)
你正在做的是你breaking
离开了循环。这会将其发送出循环并返回到方法的其余部分,在这种情况下,该方法为空。你没有指示它做任何事情。我想你的意思是:
if (UserID == EnteredUserID && (Password == EnteredPassword)
&& (StudentNumber == EnteredStudentNumber)) {
System.out.println("Athentication complete!");
System.out.println("***Elevator access granted!***");
System.out.println("Welcome...");
Elevator a = new Elevator(); //actually do something
Elevator.selectfloor();
break;
}
即假设Elevator
是一个类。
答案 1 :(得分:0)
三次失败后,for循环结束,因此方法返回并退出程序。成功登录后,您将退出for循环...方法返回并退出程序。
您希望在成功登录时发生什么?以及实现这一目标的代码在哪里?