繁体   English   中英

如何在不跳过的情况下读取 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 为什么我的代码中的 nextLine() 被跳过了? 当您使用Scanner.next()方法时,它会跳过您输入的第一个单词之后的任何内容。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM