如何在Java中进行多行输入 [英] How to take multi-line input in Java

查看:829
本文介绍了如何在Java中进行多行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java中的多行用户输入并将行拆分为array,我需要用它来解决在线法官的问题.我正在使用Scanner进行输入.我无法确定输入的结尾.我总是遇到一个无限循环,因为我不知道输入的大小(即行数)

I'm trying to take multi-line user input in Java and split the lines into an array, I need this to solve a problem for an online judge. I'm using a Scanner to take input. I cant determine the end of input. I always get an infinite loop, since I don't know the size of input (i.e number of lines)

使用空字符串终止输入(单击Enter)仍然是一个无限循环.下面提供的代码.

Terminating input with an empty String (clicking enter) is still an infinite loop. Code provided below.

  public static void main(String[] args) {

        ArrayList<String> in = new ArrayList<String>();
        Scanner s = new Scanner(System.in);

        while (s.hasNextLine() == true){
            in.add(s.nextLine());
            //infinite loop
        }
    }

我什至不知道为什么循环第一次执行.我相信hasNextLine()第一次应该是假的,因为还没有输入.任何帮助或澄清表示赞赏.

I'm not even sure why the loop executes the first time. I believe the hasNextLine() should be false the first time ,since no input was taken yet. Any help or clarification appreciated.

推荐答案

您可以使用空行作为循环中断器:

You could use the empty line as a loop-breaker:

while (s.hasNextLine()){ //no need for "== true"
    String read = s.nextLine();
    if(read == null || read.isEmpty()){ //if the line is empty
        break;  //exit the loop
    }
    in.add(read);
    [...]
}

这篇关于如何在Java中进行多行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆