我试图这样做,以便如果用户名和/或密码不正确,程序将再次运行它,而不是仅仅在 else 语句中执行打印命令。我尝试在 else 语句中放入另一个 while 循环,并在其中嵌套 if 语句来检查其中的用户名和密码,但后来我意识到我必须将 if 语句中的所有代码复制到 else 语句中,这显然看起来就像这不是正确的解决方案并且可能非常笨拙。让程序重新开始运行的正确方法是什么?
// Declare Variables
Scanner input = new Scanner(System.in);
String username;
String password;
String calculator = "calculator";
String renameUser = "renameUser";
String renamePass = "renamePass";
String getIp = "getIp";
String exit = "exit";
String command;
// Prompt User to login
System.out.println("Username: ");
username = input.nextLine();
System.out.println("Password: ");
password = input.nextLine();
if (username.equals("admin") && password.equals("admin") ) // Must use the equals method of string class to compare, == operator will NOT work.
{
System.out.println("Success! Welcome " + username + "!");
while (true) // Infinite loop using the true statement
{ command = input.nextLine();
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{ // renameUser code here
if (command.equals(renamePass))
{ // renamePass code here
if (command.equals(getIp))
{ // getIp code here
if(command.equals(exit))
{
break;
}
System.out.println("Logging out!");
}
}
}
}
}
}
else
{
System.out.println("Wrong username or password, please try again.");
}
}
}
最佳答案
思考下面的逻辑
if (command.equals(calculator))
{ // calculator code here
if (command.equals(renameUser))
{
如果command
等于calculator
那么它怎么会等于renameUser
你应该拥有它
if (....) {
}
else if (...) {
}
语句或作为 switch 语句
关于java - 用 Java 重新运行我的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37693206/