简体   繁体   中英

Why scanner can't read any (empty) space between words (in my specific case)?

My program will ask the user to enter his/her name. At the moment my scanner object can read only a single word. But if the user enters muliple words (let's say someone's full name), then it throws exception. Like this:

例外

How can I solve this?

My code:

    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);

            }

        }

    }

}

You need to change

name = sc.next();

sc.next() will read only till the space nothing after that

name = sc.nextLine();

sc.nextLine() will read the whole line.

Note you need to be careful of skipping read Scanner is skipping nextLine() after using next(), nextInt() or other nextFoo() methods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM