在java中输入未知大小的数组

时间:2015-10-28 09:14:08

标签: java arraylist input

如何输入长度可能不同的数组?输入是空格分隔的,当我按下

时结束
public class ArrayInput {
    public static void main(String args[]){
        ArrayList<Integer> al = new ArrayList<Integer>();
        Scanner sc = new Scanner(System.in);
        while(){//what condition to use here?
            al.add(sc.nextInt());
        }
    }
}

一个例子是:

1 2 5 9 7 4  //press enter here to mark end of input

2 个答案:

答案 0 :(得分:2)

使用sc.nextLine()阅读整行,然后使用split()阅读\\s+。这样,您不必担心输入的大小(元素的数量)。使用Integer.parseInt()将字符串解析为整数。

答案 1 :(得分:2)

由于您的所有输入都在一行中,您可以读取整行,然后将其拆分为整数:

String line = sc.nextLine();
String[] tokens = line.split(" ");
int[] numbers = new int[tokens.length];
for (int i=0; i<numbers.length;i++)
    numbers[i] = Integer.parseInt(tokens[i]);