【问题标题】:How to read whole line input in Java without skipping it (scanner.next())如何在 Java 中读取整行输入而不跳过它(scanner.next())
【发布时间】:2021-01-20 14:01:59
【问题描述】:

我正在做一个非常基本的 Java 程序:

import java.util.Scanner;

public class App {
    
    private static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {
        int nbrFloors = 0;
        int nbrColumns = 0;
        int nbrRows = 0;

        System.out.println("So you have a parking with " + Integer.toString(nbrFloors) + " floors " + Integer.toString(nbrColumns) + " columns and " + Integer.toString(nbrRows) + " rows");
        System.out.print("What's the name of your parking ? ");
        String parkName = sc.next(); //or sc.nextLine() ?
        System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");
        float intPrice = Float.parseFloat(sc.next());
        Parking parking = new Parking(nbrFloors, nbrColumns, nbrRows, parkName, intPrice);
        
    }
}

正如您在第 16 行看到的那样,我使用 Scanner.next() 方法,因为使用 Scanner.nextLine() 会跳过用户输入。但是我在这个线程Java Scanner why is nextLine() in my code being skipped? 中了解到,当您使用Scanner.next() 方法时,它会跳过您输入的第一个单词之后的任何内容。

所以我想知道如何在不跳过它(因为Scanner.nextLine() 这样做)并读取整个输入的情况下请求用户输入?

【问题讨论】:

    标签: java java.util.scanner


    【解决方案1】:

    您的代码会跳过用户输入,因为 nextLine() 方法会读取一行直到 newLine 字符(回车)。所以在 nextLine() 完成读取后,回车实际上停留在输入缓冲区中。这就是为什么当您调用 sc.next() 时,它会立即从输入缓冲区读取回车并终止读取操作。您需要做的是在读取行操作后隐式清除输入缓冲区。为此,只需在第 16 行之后调用一次 sc.next()。

        System.out.print("What's the name of your parking ? ");
        String parkName = sc.nextLine();
        sc.next();
        System.out.print("How much should an hour of parking ? If you want your parking to be free please type in '0' : ");
    
    

    【讨论】:

    • 哦,谢谢。 Java/Scanner 有一个很奇怪的行为:为什么在输入缓冲区中保留回车?
    • 这就是方法的设计方式。通常,您可以通过回车、空格或制表符来表示输入字符串的终止。因此这些方法将这些字符视为终止字符并读取它们遇到这些字符。类似地,在读取文件时您读取到 EOF 但实际上并未读取 EOF 本身。所以它会被抛在后面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-27
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多