如何读取 Java 中的整行输入而不跳过它 (scanner.next())

How to read whole line input in Java without skipping it (scanner.next())

我正在做一个非常基础的 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() 这样做)并阅读整个输入?

您的代码会跳过用户输入,因为 nextLine() 方法会读取一行直至换行符(回车 return)。因此,在 nextLine() 完成读取后,回车 return 实际上停留在输入缓冲区中。这就是为什么当你调用 sc.next() 时,它会立即从输入缓冲区中读取回车 return 并终止读取操作。您需要做的是在读取行操作后隐式清除输入缓冲区。为此,只需在第 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' : ");