Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 382
Tanvi Avatar asked Mar 24 '26 16:03

Tanvi


2 Answers

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]);
like image 178
Eran Avatar answered Mar 27 '26 04:03

Eran


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.

like image 21
TheLostMind Avatar answered Mar 27 '26 05:03

TheLostMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!