Java登录系统方法

时间:2018-07-09 11:47:21

标签: java

几乎可以使用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("\n\n");
        new Products().search();
        }
    }

}

在if部分中输入“ N”可以很好地工作,但是在else部分起作用之前,需要输入两次“ Y”(我知道为什么它不起作用)。

我知道这很简单,但是关于如何使其工作的任何线索?

感谢任何帮助...

4 个答案:

答案 0 :(得分:5)

这里

String Y = sc.nextLine();

您正在阅读另一行输入。您想比较已经读取的输入的相同行,该行存储在名为N的变量中。如果您给它起一个更好的名字,它将更加清楚。

String line = sc.nextLine();

if ("N".equals(line)) {
    Login();
} else if ("Y".equals(line)) {
    System.out.print("Email address: ");
    ...
}

答案 1 :(得分:3)

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("\n\n");
    new Products().search();
    }
}

答案 2 :(得分:1)

您不需要第二个nextLine。继续使用String N(也许将其重命名为输入),并继续检查Y

答案 3 :(得分:1)

如果您输入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()