扫描仪 nextLine() 在 System.in.read() 之后不起作用



我有以下代码,如果我在Scanner之前使用System.in.read(),我将面临一个问题。
然后跳过nextLine()函数,光标移动到最后。

import java.util.Scanner;
public class InvoiceTest{
public static void main(String [] args) throws java.io.IOException {
    System.out.println("Enter a Charater: ");
    char c = (char) System.in.read();
    Scanner input = new Scanner(System.in);
    System.out.println("Enter id No...");
    String id_no = input.nextLine();
    System.out.println("Charater You entered "+ c +" Id No Entered "+ id_no);
    }
}

在输入字符(System.in.read())时不使用换行符,因此input.nextLine()将使用它并跳过它。

解决方案:

在读取id的输入之前先使用新的行字符。

System.out.println("Enter a Charater: ");
    char c = (char) System.in.read();
    Scanner input = new Scanner(System.in);
    System.out.println("Enter id No...");
    input.nextLine(); //will consume the new line character spit by System.in.read()
    String id_no = input.nextLine();
    System.out.println("Charater You entered "+c+" Id No Entered "+id_no);
    }

EJP注释如下:

不要将System.in.read()与new Scanner(System.in)混合使用。选择其中之一。

好的忠告啊!

那么为什么混合从流中读取和使用Scanner是一个坏主意呢?

因为Scanner操作通常会提前读取输入流中的,将未使用的字符保留在内部缓冲区中。因此,如果您执行Scanner操作,然后在流上调用read(),那么read()很有可能(实际上)跳过字符。这种行为很可能令人困惑和不可预测。并且取决于输入字符的实际来源

最新更新