我几乎已经用Java实现了这个登录系统,但我遇到了这个方法的问题:
public void Register() {
Scanner sc = new Scanner(System.in);
System.out.print("Register? (Y/ N)n");
String N = sc.nextLine();
if ("N".equals(N)) {
Login();
} else {
String Y = sc.nextLine();
if ("Y".equals(Y)) {
System.out.print("Email address: ");
String string = sc.nextLine();
System.out.print("Password: ");
String string2 = sc.nextLine();
System.out.print("nn");
new Products().search();
}
}
}
在if部分输入"N"非常有效,但在else部分工作之前需要输入两次"Y"(我理解为什么它不起作用(。
我知道这很简单,但有什么线索可以让它发挥作用吗?
感谢任何帮助。。。
此处为
String Y = sc.nextLine();
你正在阅读另一行输入。您想要比较已经读取的同一行输入,该行存储在一个名为N
的变量中。如果你给它一个更好的名字,它会更清楚。
String line = sc.nextLine();
if ("N".equals(line)) {
Login();
} else if ("Y".equals(line)) {
System.out.print("Email address: ");
...
}
这个String N = sc.nextLine();
再次此
字符串Y=sc.nextLine((;
无需使用两次输入法
将变量名称更改为有意义的
试试这种方式
它肯定会起作用的。。
public void Register() {
Scanner sc = new Scanner(System.in);
System.out.print("Register? (Y/ N)n");
String input = sc.nextLine();
if ("N".equals(input)) {
Login();
} else {
// removed 'String Y = sc.nextLine();'
if ("Y".equals(input)) {
System.out.print("Email address: ");
String string = sc.nextLine();
System.out.print("Password: ");
String string2 = sc.nextLine();
System.out.print("nn");
new Products().search();
}
}
您不需要第二个nextLine
。继续使用String N
(可能将其重命名为input(,并继续检查Y
。
如果您键入Y
,它将保存在N
变量中,它将进入else
部分,在这里您再次询问用户,您不需要
你必须接受输入并测试它,而不知道它的N或Y
String choice = sc.nextLine();
if ("N".equals(choice)) {
Login();
} else if("Y".equals(choice)){
System.out.print("Email address: ");
String string = sc.nextLine();
...
}else{
System.out.println("Wrong choice");
}
还有
- 为变量指定更重要的名称,不是
string, string2
,而是email, pwd
- 方法名称必须以
lowerCaser
:Login()
>>login()
开头