首页 > 解决方案 > 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?

标签: javaarraylistwhile-loop

解决方案


您需要一个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();是一种读取等待输入的便捷方式。


推荐阅读