java输入 多行,如何在Java中进行多行输入

本文讨论了Java中如何避免Scanner读取多行用户输入时导致的无限循环,重点介绍了在hasNextLine()方法中加入空行判断作为退出条件的解决方案。通过实例代码和解析,帮助开发者理解并避免此类常见问题。
摘要由CSDN通过智能技术生成

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)

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

public static void main(String[] args) {

ArrayList in = new ArrayList();

Scanner s = new Scanner(System.in);

while (s.hasNextLine() == true){

in.add(s.nextLine());

//infinite loop

}

}

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

[...]

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值