【发布时间】:2015-03-10 22:31:21
【问题描述】:
我正在创建一个非常基本的登录系统来测试 switch-case,但是我遇到了一个问题,即除非初始化变量,否则 case 2 无法运行。在我的程序中,案例 1 是创建帐户,案例 2 是登录帐户。但是,案例 2 可以立即访问,但除非已创建帐户的详细信息,否则不会运行。我正在寻找一种拒绝访问案例 2 的方法,除非案例 1 已首先完成。这可能吗?这是我的登录系统;
public class User {
private static Scanner in;
public static void main(String[] args) {
in = new Scanner(System.in);
int userChoice;
boolean quit = false;
do {
System.out.println("1. Create Account");
System.out.println("2. Login");
System.out.print("3. Quit");
userChoice = in.nextInt();
switch (userChoice) {
case 1:
String firstName;
String secondName;
String email;
String username;
String password;
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 (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.");
break;
}
System.out.println();
} while (!quit);
System.out.println("Bye!");
}
}
我目前收到此错误;
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The local variable username may not have been initialized
The local variable password may not have been initialized
at User.main(User.java:68)
【问题讨论】:
-
如果用户先输入 2 会发生什么?
-
可以尝试登录,但用户没有登录凭据。
-
要做的第一件事:在编译之前不要尝试运行您的代码!
-
这段代码让我很困惑...为什么不将其更改为 if...else if... 语句,并使用布尔值控制他们是否已创建帐户。
-
记录“案例 1”的变量已经运行,并且如果没有运行
if语句来防止“案例 2”?这真的需要成为堆栈溢出问题吗?
标签: java variables switch-statement