Java扫描器跳过输入nextLine()而不是next()

这个问题在这里已经有了答案:

  • 扫描仪使用next()或nextFoo()后跳过nextLine()? 15个答案

  • 您必须清除Scanner,以便使用reader.nextLine(); , 喜欢这个 :

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

    编辑

    为什么'next()'忽略仍然留在扫描仪中的 n?

    你会在这里理解这个例子:

    下一个()

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

    产量

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

    产量

    Hello World!
    Hello Java!
    

    所以我们可以理解next()逐字读取,因此它不会像nextLine()那样使用

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

    上一篇: Java scanner skips input nextLine() but not next()

    下一篇: Trouble with order of reading next line with Scanner