简体   繁体   English

JAVA文件结束多行输入

[英]JAVA End Of File multiple lines input

When I run the code for this program I get: 当我运行该程序的代码时,我得到:

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

        }
     }
 }

the output for each input, for example 每个输入的输出,例如

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

How do I set up the program to allow multiple lines to be entered before declaring end of file? 如何设置程序以允许在声明文件结束之前输入多行? like : 喜欢 :

input: abc
       xyz
       aaa 
       ...etc

output: ABC
        XYZ
        AAA
        ...etc

I have a feeling I'm gonna be embarrassed when I find out! 当我发现时我会感到尴尬!

I appreciate any help, thank you. 感谢您的帮助,谢谢。

You want the output only at the end, so I suggest storing the input somewhere eg a List, and only printing them out when the end of the input is reached. 您只希望在最后输出,因此我建议将输入存储在某个位置(例如列表),并仅在到达输入末尾时将它们打印出来。

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

   }
}

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

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