有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在多个数组列表中添加数据?

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

上述程序的输出为:

Number of Array lists
3
Enter the values
1
2
3
done
[1, 2, 3]
Enter the values
[]
Enter the values
[]

正如我们所见,当我输入任何字符或字符串(在本例中,我输入了“done”)时,while循环退出,其他两个数组列表保持为空。我还想把int值添加到剩下的数组列表中。我该怎么做


共 (2) 个答案

  1. # 1 楼答案

    can you explain what is your requirement? Is it you want to just see how to read and add values in list or just to put some random values, check if this helps you.
    
    System.out.println("Number of Array lists");
            int total_arraylists = input.nextInt();
            ArrayList<Integer> lists[] = new ArrayList[total_arraylists];
            ArrayList<Integer> list = null;
            for( int i = 0; i < total_arraylists; i++) {   
                list = new ArrayList<Integer>();
                for(int j=1; j<=3; j++) {
                    list.add(j);
                }
                lists[i] = list;
            }
            System.out.println("----- result-----");
            for(int i =0 ;i< total_arraylists;i++) {
                System.out.println(lists[i]);
            }
    
    
    Output::
    
    Number of Array lists
    3
    ----- result-----
    [1, 2, 3]
    [1, 2, 3]
    [1, 2, 3]
    
  2. # 2 楼答案

    hasNextInt()总是返回true。所以所有的数字都会添加到你的第一个列表中

    import java.io.*;
    import java.util.*;
    
    class Hello{
        public static void main(String args[]){
            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");
                int array_length = input.nextInt();
                while(array_length-- > 0){
                    lists[i].add(input.nextInt());
                }
                System.out.println(lists[i]);
            }
        }
    }
    

    输入:

    3
    3
    1
    2
    3
    2
    4
    9
    2
    9
    12
    

    输出:

    Number of Array lists
    Enter the values
    [1, 2, 3]
    Enter the values
    [4, 9]
    Enter the values
    [9, 12]