简体   繁体   English

在Java中从控制台读取多行,最后一行出现问题

[英]Read multiple lines from console in Java, issue with last line

I want to load multiple lines from console. 我想从控制台加载多行。 I paste text into console, this text has more lines. 我将文本粘贴到控制台,此文本有更多行。 Last line doesn't want to load, its because there is missing \\n. 最后一行不想加载,因为缺少\\ n。 I am not able to add \\n in console, because when I paste it, it runs immediately. 我无法在控制台中添加\\ n,因为当我粘贴它时,它会立即运行。 Another issue is that while doesn't want to end. 另一个问题是,虽然不想结束。 It loads everything expect last line and doesn't end. 它加载了最后一行的所有内容并且没有结束。

        Scanner input = new Scanner(System.in); 
        List<String> lines = new ArrayList<String>();
        String lineNew;

        while (input.hasNextLine()) {
            lineNew = input.nextLine();
            System.out.println(lineNew);
            lines.add(lineNew);         
        }

你应该按ctrl + z(ctrl + d)来终止它。

You could just add a check if your input is too short and if yes, break. 如果您的输入太短,您可以添加一个检查,如果是,则中断。

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

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

        Scanner input = new Scanner(System.in);
        List<String> lines = new ArrayList<String>();
        String lineNew;

        while (input.hasNextLine()) {
            lineNew = input.nextLine();
            if (lineNew.isEmpty()) {
                break;
            }
            System.out.println(lineNew);
            lines.add(lineNew);
        }

        System.out.println("Content of List<String> lines:");
        for (String string : lines) {
            System.out.println(string);
        }
    }
}

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

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