Both next() and nextLine() not helping to store name with spacing

I am currently using a Scanner to record the user input which is a String and print it out. If the user input is a single name such as Alan, it works fine. If I enter a name with spacing such as Alan Smith, it returns an error saying InputMisMatchException.

I read around similar cases here and they advised to use nextLine() instead of next(). It made sense but that doesn't work for me either. When I use a nextLine(), it immediately skips the step where I enter the name and goes back to the starting of the loop asking me to input choice again. Please advice how I can correct this. Thank you.

import java.io.IOException;
import java.util.Scanner;

public class ScannerTest {
    static String name;
    static Scanner in = new Scanner(System.in);
    static int choice;

    public static void main(String[] args) {      
        while(choice != 5){
            System.out.print("nEnter Choice :> ");
            choice = in.nextInt();

            if(choice == 1){
                try{
                    printName();
                }
                catch(IOException e){
                    System.out.println("IO Exception");
                }
            }
        } 
    }  
    private static void printName()throws IOException{
        System.out.print("nEnter name :> ");
        name = in.next();
        //name = in.nextLine(); 
        if (name != null){
            System.out.println(name);
        }
    }  
}  

Try this instead: add name = in.nextLine(); after choice = in.nextInt(); .

Then try replacing name = in.next(); with name = in.nextLine();

Explanation: After the scanner calls nextInt() it gets the first value and leaves the rest of the string to the n . We then consume the rest of the string with nextLine() .

The second nextLine() is then used to get your string parameters.


The problem is easy: when you prompt the user to enter his/her choice, the choice will be an int followed by a new line (the user will press enter). When you use in.nextInt() to retrieve the choice, only the number will be consumed, the new line will still be in the buffer, and, so, when you call in.nextLine() , you will get whatever is between the number and the new line (usually nothing).

What you have to do, is call in.nextLine() just after reading the number to empty the buffer:

choice = in.nextInt();

if (in.hasNextLine())
    in.nextLine();

before to call name = in.next(); do this in = new Scanner(System.in); the object need rebuild itself because already has value. good luck

链接地址: http://www.djcxy.com/p/96068.html

上一篇: Java扫描器不会等待用户输入

下一篇: next()和nextLine()都不能以间距存储名称