Oscar F
Oscar F

Reputation: 323

How can a user input an array of any length in java?

I'm writing a program in java that requires the user to input a series of numbers, for example 1 2 3 4 .. until the user decides to stop and press enter. Normally what I would do is something like this

Scanner scan = new Scanner (System.in);    
int[] array = new int[i];    
for (int x = 0; x < i; ++x)    
{    
    array[i] = scan.nextInt();      
}    

The problem is, in most cases i would have a set value. For example, I would ask how many numbers are going to be entered or something like that and that would be stored into i. In this case, i doesn't have a set value to begin with. The user should have the ability to enter as many numbers as he/she wants. Any suggestions?

I tried this and I know the problem with it is that it will never exit the loop but maybe I'm on the right track or something so I'll post it here anyway.

for (int i = 0; i < x; i++, x++)    
{    
    numbers[i] = scan.nextInt();    
    numbers = new double[x];                    
}

Upvotes: 0

Views: 8956

Answers (5)

Seagull
Seagull

Reputation: 13859

You can use one of dynamic Collections, as described above, and then convert to array using

int[] arr = list.toArray(new int[0]);

Also note, that scanner is very slow. There are several solutions, using BufferedStreams, to achieve better performance. There is one in article above.

Upvotes: 0

Corjava
Corjava

Reputation: 340

It sounds to me that you're saying that you only want them to hit enter once to know when there are done.

If this is the case, you can save their input as a String and then use

.split(" ");

and that will break the String into an array of Strings delimiting by a space.

After this you can Parse the string array into an Int array.

Upvotes: 2

Saša Šijak
Saša Šijak

Reputation: 9291

You need to use collections. For example like this :

Scanner scan = new Scanner (System.in);
ArrayList<Integer> numbers = new ArrayList<Integer>();
while(true){
    int number = scan.nextInt();
    if(number == -1)
        break;

    numbers.add(number);
}

Also you need a way to let user stop entering numbers. For this example, entering is stopped when user types -1 for a number. Change that condition for your context.

Upvotes: 1

Paul Samsotha
Paul Samsotha

Reputation: 208954

ArayList<Integer> nums = new ArrayList<Integer>();

nums.add(userInput);

ArrayLists auto increment in size, so you don't have to set a size.

To obtain a value, you can use the get(index).

int n = nums.get(0);

Upvotes: 1

Gerardo Lastra
Gerardo Lastra

Reputation: 665

Maybe an array is not what you're looking for. Take a look at Java Collections.

In this case, the most sensible thing would be a List. There are several implementations of the List interface, each with their own advantages and disadvantages (time complexity of different operations). This would be a nice chance to read up on those things as well :).

Upvotes: 1

Related Questions