简体   繁体   中英

Input an array of unknown size in java

How do I input an array whose length may vary? The input is space delimited and ends when I press enter

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

An example would be:

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

Read the entire line using sc.nextLine() and then split() using \\\\s+ . This way, you don't have to worry about size of input (number of elements). Use Integer.parseInt() to parse Strings as integers.

Since all your input is in a single line, you can read the entire line and then split it to integers :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM