我正在寻找一种在每个案例完成后返回“菜单”的方法,并且仅在选择退出时退出/关闭程序。我假设会使用一个 while 循环,但我无法返回菜单并保持到目前为止的所有输入和进度而无需重新启动程序。到目前为止,这是我的代码;
import java.util.Scanner;
public class User2 {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int userChoice;
boolean quit = false;
String firstName = null;
String secondName = null;
String email = null;
String username = null;
String password = null;
do {
System.out.println("1. Create Account");
System.out.println("2. Login");
System.out.println("3. Quit");
userChoice = Integer.parseInt(in.nextLine());
switch (userChoice) {
case 1:
System.out.print("Enter your first name: ");
firstName = in.nextLine();
System.out.println("Enter your second name:");
secondName = in.nextLine();
System.out.println("Enter your email address:");
email = in.nextLine();
System.out.println("Enter chosen username:");
username = in.nextLine();
System.out.println("Enter chosen password:");
password = in.nextLine();
break;
case 2:
String enteredUsername;
String enteredPassword;
System.out.print("Enter Username:");
enteredUsername = in.nextLine();
System.out.print("Enter Password:");
enteredPassword = in.nextLine();
if (username != null && password != null
&& enteredUsername == username
&& enteredPassword == password)
System.out.println("Login Successfull!");
else
System.out.println("Login Failed!");
break;
case 3:
quit = true;
break;
default:
System.out.println("Wrong choice.");
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}
最佳答案
不要使用 ==
进行字符串比较使用 String.equals
例如
enteredUsername.equals (username)
甚至
enteredUsername.equalsIgnoreCase (username)
无论输入的文本大小写如何进行比较
关于java - 在每个 switch-case 之后循环回到开始,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28976665/