2016-04-03 58 views
0

当我运行此程序的代码我得到:JAVA文件结束多行输入

import java.util.Scanner; 

public class Capital { 
    public static void main(String []args) { 

     Scanner kbd = new Scanner(System.in); 

     while (kbd.hasNextLine()) { 
     String str = kbd.nextLine(); 

     System.out.println(str.toUpperCase()); 

     } 
    } 
} 

输出为每个输入,例如

input: abc 
output:ABC 
input: xyz 
output:XYZ 

如何设置程序在声明文件结束之前允许输入多行?像:

input: abc 
     xyz 
     aaa 
     ...etc 

output: ABC 
     XYZ 
     AAA 
     ...etc 

我有一种感觉,当我找到了我会感到尴尬!

我很感激任何帮助,谢谢。

+0

你是不是从文件中取输入。那么如何验证您是否已达到EOF? – Rehman

+0

尝试ctrl-z作为最后输入 – Turo

回答

0

您只希望输出结束,所以我建议将输入存储在某个地方,例如一个列表,并且只有在输入结束时才打印出来。

Scanner kbd = new Scanner(System.in); 

List<String> input = new ArrayList<>(); 
while (kbd.hasNextLine()) 
    input.add(kbd.nextLine()); 

// after all the input, output the results. 
for (String str : input) 
    System.out.println(str.toUpperCase()); 
+1

谢谢!!!!!! –

0
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

public class EndOfFile { 
public static void main(String[] args) throws IOException { 
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    int n = 1; 
    String line; 
    while ((line=br.readLine())!=null) { 
     System.out.println(n + " " + line); 
     n++; 
    } 

    } 
}