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

我与影子孤独终老i 提交于 2019-12-13 06:17:27

问题


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

回答1:


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.




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/22622464/both-next-and-nextline-not-helping-to-store-name-with-spacing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!