java中从控制台输入多行数据 按回车键结束怎么做到?

come_on_wqp 2011-01-12 08:59:47
ArrayList<String> array=new ArrayList<String>();
Scanner scn = new Scanner(System.in);

while(scn.hasNextLine()){
array.add(scn.nextLine());
}
return array;
这个怎么不行啊 请高手指点…………
...全文
3618 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
string.isEmpty()是JDK1.6以后的

Scanner scanner = new Scanner(System.in);
ArrayList<Integer> ns = new ArrayList<>();
do {
	String string = scanner.nextLine();
	if (string.equals("")) {
		break;
	}
	ns.add(Integer.valueOf(string));
} while (true);

System.out.println(ns);
  • 打赏
  • 举报
回复
Scanner scanner = new Scanner(System.in);
		ArrayList<Integer> nsArrayList = new ArrayList<>();
		do {
			String string = scanner.nextLine();
			if (string.isEmpty()) {
				break;
			}
			nsArrayList.add(Integer.valueOf(string));
		} while (true);
qybao 2011-01-12
  • 打赏
  • 举报
回复
多行输入,应该有个结束符标志,否则,你按回车,系统怎么知道你是输入结束还是要继续输入下一行呢?
像LS那样,用个end字符串作为输入结束标志
happyfmy 2011-01-12
  • 打赏
  • 举报
回复
按回车键是输入下一行 可以做个判断
你的newxLine()方法不对

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

String line;
while (!"end".equals(line = scn.nextLine())) {
array.add(line);

}

for(String str : array){
System.out.println(str);
}

50,535

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧