简体   繁体   English

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

[英]Scanner nextLine() doesn't work after System.in.read()

I have following code and am facing a problem if I use System.in.read() before Scanner . 我有以下代码,如果在Scanner之前使用System.in.read() ,则会遇到问题。
Then the cursor moves at the end by skipping nextLine() function. 然后,通过跳过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);

    }
}

You are not consuming the newline character upon entering your character( System.in.read() ) thus the input.nextLine() will consume it and skip it. 输入字符( System.in.read() )时不会消耗换行符,因此input.nextLine()将消耗它并跳过它。

solution: 解:

consume the new line character first before reading the input of for the id. 在读取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 comments thus: 因此,EJP评论:

Don't mix System.in.read() with new Scanner(System.in). 不要将System.in.read()与新的Scanner(System.in)混合使用。 Use one or the other. 使用一个或另一个。

Good advice! 好建议!

So why is it a bad idea to mix reading from the stream and using Scanner ? 那么,为什么将流中的读取内容与Scanner混合使用Scanner是一个好主意呢?

Well, because Scanner operations will typically read ahead on the input stream, keeping unconsumed characters in an internal buffer. 好吧,因为Scanner操作通常会提前读取输入流,从而将未使用的字符保留在内部缓冲区中。 So if you do a Scanner operation followed by a call to read() on the stream, there is a good chance that the read() will (in effect) skip over characters. 因此,如果您执行Scanner操作, 然后在流上调用read() ,则read()可能(实际上)将跳过字符。 The behaviour is likely to be confusing and unpredictable ... and dependent on where the input characters are actually coming from. 该行为可能会造成混淆和不可预测……并取决于输入字符的实际来源。

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

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