JAVA End Of File多行输入

时间:2016-04-03 06:45:10

标签: java while-loop jvm eof uppercase

当我运行此程序的代码时,我得到:

 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

我有一种感觉,当我发现时,我会感到尴尬!

感谢您的帮助,谢谢。

2 个答案:

答案 0 :(得分: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++;
    }

   }
}
相关问题