简体   繁体   English

在Java中使用Scanner提供多行输入

[英]Providing multiple lines of input using Scanner in java

My input will be 我的输入将是

12
4.0
has to be concatenated with this input

My Expected output is 我的预期输出是

16
8.0
RandomString has to be concatenated with this input

My code which tries to do this is follows 我的尝试这样做的代码如下

        int i = 4;
        double d = 4.0;
        String s = "RandomString";

        Scanner scan = new Scanner(System.in);
        int j = scan.nextInt(); 
        double e = scan.nextDouble();
        String str = scan.nextLine();
        int resInt = i + j; double resDouble = d + e; String resString = s +" "+ str;
        System.out.println(resInt);
        System.out.println(resDouble);
        System.out.println(resString);

        scan.close();

This behaves differently. 这表现不同。 As soon as I enter two lines of input it is giving me output. 一旦输入两行输入,它就会给我输出。 Not waiting for third line of my input. 不等待我输入的第三行。 So now my output is 所以现在我的输出是

12
4.0
16
8.0
RandomString

Primitive data types like int, double does not consume Enter key/End of line. 原始数据类型(如int,double)不会占用Enter键/行尾。 That's why enter typed after keying integer is taken as value from buffer for your nextLine(). 这就是为什么将键入整数后键入的enter作为nextLine()的缓冲区中的值。

When you want to use the same scanner object with nextInt(), and a nextLine(), It doesn't work well. 当您想将相同的扫描仪对象与nextInt()和nextLine()一起使用时,它将无法正常工作。

There are two solutions to this, Solutions are to create another scanner to read string OR give an extra nextLine() before attempting to read the random string as given below. 有两种解决方案,解决方案是创建另一个扫描程序以读取字符串,或在尝试读取随机字符串之前提供额外的nextLine(),如下所示。

Scanner scan = new Scanner(System.in);
int j = scan.nextInt();
double e = scan.nextDouble();
scan.nextLine();
String str = scan.nextLine();

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

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