首页 > 解决方案 > 如何在 Java 中读取整行输入而不跳过它(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()方法是因为 using会Scanner.nextLine()跳过用户输入。但是我在这个线程Java Scanner 中了解到为什么我的代码中的 nextLine() 被跳过了?当您使用该Scanner.next()方法时,它会跳过您输入的第一个单词之后的任何内容。

所以我想知道如何在不跳过它(因为Scanner.nextLine()那样做)和阅读整个输入的同时要求用户输入?

标签: javajava.util.scanner

解决方案


您的代码会跳过用户输入,因为 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' : ");


推荐阅读