2016-09-24 62 views
0

我的输入将是提供在Java中使用扫描仪输入的多行

12 
4.0 
has to be concatenated with this input 

我的预期输出是

16 
8.0 
RandomString has to be concatenated with this input 
如下

我它试图做到这一点是代码

 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(); 

这表现有所不同。只要我输入两行输入,它就会给我输出。不等待我的输入的第三行。所以现在我的输出是

12 
4.0 
16 
8.0 
RandomString 

回答

1

原始数据类型如int,double不消耗回车键/行结束。这就是为什么在keying整数之后的输入类型被作为nextLine()的缓冲区的值。

如果您想在nextInt()和nextLine()中使用相同的扫描仪对象,则效果不佳。

有两种解决方案,解决方案是创建另一个扫描器读取字符串或给出额外的nextLine(),然后尝试读取随机字符串,如下所示。

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