Java scanner skips input nextLine() but not next()

This question already has an answer here:

  • Scanner is skipping nextLine() after using next() or nextFoo()? 15 answers

  • You have to clear your Scanner so you can use reader.nextLine(); , like this :

    if (input % 2 == 0) {
        System.out.println("The input was even");
    } else if (input % 2 == 1) {
        System.out.println("The input was odd");
    } else {
        System.out.println("The input was not an integer");
    }
    
    
    reader.nextLine();//<<--------------Clear your Scanner so you can read the next input
    
    
    //example with user string input
    System.out.println("Verify by typing the word 'FooBar': ");
    String input2 = reader.nextLine();
    System.out.println("The string equal 'FooBar': " + input2.equals("FooBar"));
    

    Edit

    why does 'next()' ignore the n still left in the scanner?

    You will understand with this example here :

    next()

    public static void main(String[] args) {
        String str = "Hello World! Hello Java!";
    
        // create a new scanner with the specified String Object
        Scanner scanner = new Scanner(str);
    
        while(scanner.hasNext()){
            System.out.println( scanner.next());
        }
        scanner.close();
    }
    

    Output

    Hello
    World!
    Hello
    Java!
    

    nextLine()

    public static void main(String[] args) {
        String str = "Hello World!nHello Java!";
    
        // create a new scanner with the specified String Object
        Scanner scanner = new Scanner(str);
    
        while(scanner.hasNext()){
            System.out.println( scanner.nextLine());
        }
        scanner.close();
    }
    

    Output

    Hello World!
    Hello Java!
    

    So we can understand that next() read word by word so it does not use n like nextLine()

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

    上一篇: 我在运行时收到错误

    下一篇: Java扫描器跳过输入nextLine()而不是next()