java - How to add data in Multiple Array lists?
问题描述
Scanner input = new Scanner(System.in);
System.out.println("Number of Array lists");
int total_arraylists = input.nextInt();
ArrayList<Integer> lists[]=new ArrayList[total_arraylists];
for( int i = 0; i < total_arraylists; i++){
lists[i]=new ArrayList<Integer>(i);
System.out.println("Enter the values");
while(input.hasNextInt()){
lists[i].add(input.nextInt());
}
System.out.println(lists[i]);
}
Output of the above program is:
Number of Array lists
3
Enter the values
1
2
3
done
[1, 2, 3]
Enter the values
[]
Enter the values
[]
As we can see, when I enter any character or string (in this case,I entered "done"), the while loop exits and the other 2 Array lists remain empty. I want to add int values to those remaining Array lists too. How can I do it?
解决方案
您需要一个input.next();
after 内部循环来“吃掉”“完成”响应:
for( int i = 0; i < total_arraylists; i++)
{ lists[i]=new ArrayList<Integer>(i);
System.out.println("Enter the values");
while(input.hasNextInt())
{
lists[i].add(input.nextInt());
}
input.next(); //<----- Get past the "done"
System.out.println(lists[i]);
}
否则,当您返回获取下一个列表的数据时,input.hasNextInt()
会看到“完成”一词正在等待读取;“完成”,当然,不是int
那么hasNextInt()
会立即返回false
。Doinginput.next();
是一种读取等待输入的便捷方式。
推荐阅读
- java - javax.crypto.BadPaddingException:使用 Java RSA 加密时出现解密错误
- shortest-path - 必须通过节点的最短路径
- python - 为什么我们必须在自定义用户 django 模型中包含人员和管理字段?
- apache-spark - 如何为 spark-shell 设置 YARN 队列?
- node.js - 使用 Express.js,我如何根据任何请求发送文件?
- css - Gulp 4 编译 scss 创建空的 css 文件,但 sass 编译正确
- visual-studio - CZKEM 不包含定义(zkemkeeper 相关)
- python - 如何制作一个函数,使其根据输入中包含的单词进行过滤
- regex - 如何与没有内容的正则表达式“反向匹配”?
- linux - 使用 DotNet Core 开发的应用程序是否有自动更新程序?