在我可以解析用户输入之前,IDE会打印两行

时间:2019-11-20 04:03:30

标签: java java.util.scanner

所以我目前很难解决这个问题。简而言之,我正在尝试为一个类创建一个银行应用程序。我正在编写一种打印并获取用户输入的方法,但是打印行会在获得输入之前先打印出这两行。这是我的实现。

boolean done = false; 
        while(!done) {
            System.out.println("Welcome to Running Bank"
                        + "\nWhat would you like to do?"
                        + "\n1-Create Account"
                        + "\n2-Log-In"
                        + "\n3-Exit");
            choice = scanner.nextInt();
            switch(choice) {
            case 1:
                System.out.println("Input your username(No more than 15 characters: ");
                Username = scanner.nextLine();
                System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
                Password = scanner.nextLine();
        }
    }
}

我希望它要做的是打印出“输入您的用户名”,然后在得到用户的输入后,再打印下一行。但是,现在发生的情况是,两行都可以打印,而我可以放任何东西。 谢谢你。

1 个答案:

答案 0 :(得分:0)

boolean done = false; 
        while(!done) {
            System.out.println("Welcome to Running Bank"
                        + "\nWhat would you like to do?"
                        + "\n1-Create Account"
                        + "\n2-Log-In"
                        + "\n3-Exit");
            choice = scanner.nextInt();
            scanner.nextLine();
            switch(choice) {
            case 1:
                System.out.println("Input your username(No more than 15 characters: ");
                Username = scanner.nextLine();
                System.out.println("Input your password(Must be at least 8 characters and not over 24): ");
                Password = scanner.nextLine();
        }
    }
}

现在应该可以使用。输入scanner.nextLine()

后,我添加了choice