java - 为什么扫描仪无法读取单词之间的任何(空)空格(在我的具体情况下)?

标签 java java.util.scanner user-input

我的程序将要求用户输入他/她的名字。目前我的扫描仪对象只能读取一个单词。但是,如果用户输入多个单词(假设某人的全名),则会抛出异常。像这样:

Exception

我该如何解决这个问题?

我的代码:

    public class BankApp_Assignment {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        int userChoose;
        String name = null;
        int accNum = 0;
        double InitiateAmount = 0;
        double newAmm = 0;

        double depOrWith = 0;
        System.out.println("WELCOME TO OUR BANK!\n\n"
                + "...................\n"
                + "...................\n\n"
                + "Choose your optiin:\n"
                + "1. Create new account\n"
                + "2. Deposit\n"
                + "3. View details\n"
                + "4. Quit\n\n");
        while (true) {
            userChoose = sc.nextInt();

            if (userChoose == 1) {

                System.out.println("Enter your full name:");

                name = sc.next();
                System.out.println("Choose an account number:");

                accNum = sc.nextInt();
                System.out.println("Enter an initiating amount:");

                InitiateAmount = sc.nextDouble();
                System.out.println("\n-----------\n"
                        + "------------");
            } else if (userChoose == 2) {

                System.out.println("Enter negative value to withdraw and positive to deposit");
                depOrWith = sc.nextInt();
                if (depOrWith < 0) {

                    newAmm = InitiateAmount + depOrWith;
                } else {

                    newAmm = InitiateAmount + depOrWith;
                }

                System.out.println("\n-----------\n"
                        + "------------");

            } else if (userChoose == 3) {

                System.out.println("Your name: " + name);
                System.out.println("Your account number: " + accNum);
                System.out.println("Your current balance: " + newAmm);
                System.out.println("\n-----------\n"
                        + "------------");
            } else if (userChoose == 4) {

                System.exit(0);

            }

        }

    }

}

最佳答案

你需要改变

name = sc.next();

sc.next() 只会读取,直到后面没有任何内容

name = sc.nextLine();

sc.nextLine() 将读取整行。

请注意,您需要小心跳过阅读 Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods .

关于java - 为什么扫描仪无法读取单词之间的任何(空)空格(在我的具体情况下)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29433706/

相关文章:

java - 当我为json添加配置时,Spring MVC应用程序中断

java - 如何使用 Scanner.nextLine()

python - 使用用户输入创建列表?销售计划,输入销售7天

java - Google API v3 检索所有联系人

java - 将位图添加到布局时,仅显示 for 循环中的第一个图像

java - java中一个类的内存分配?

java - Scanner.nextInt(x) 抛出 PatternSyntaxException

Java从用户处获取用户输入

php - 你如何实现一个好的亵渎过滤器?

php - 来自 HTML 表单的 MySQL 查询 - 输入可以使用通配符吗?