I’m trying to write a program that scans in values from the console and stores them in the array. I’m trying to allow the user to specify the length of the array using the scanner. An array length as you know, can only be positive, so I’m trying to check, here’s what I have so far that in my mind should be working.
int[] array;
int index = 0;
max = new Scanner(System.in);
System.out.println("How long is your array?");
while (!max.hasNextInt() || max.nextInt() <=0 )
{
System.out.println("Arrays aren't negative, unless your's is " +
"smaller then physically posible, try again");
max.next();
}
maxSize = max.nextInt();
array = new int[maxSize];
System.out.println("Enter up to " + maxSize + " integers");
input = new Scanner(System.in);
while(input.hasNextInt())
{
array[index] = input.nextInt();
index++;
}
return array;
It’s working somewhat, here’s the output
How long is your array?
-2
Arrays aren’t negative, unless your’s is smaller then physically posible, try again
-3
-4
Arrays aren’t negative, unless your’s is smaller then physically posible, try again
2
3
4
Enter up to 4 integers
Any help is appreciated, and also it does not seem to be storing the array at all so any help with that is appreciated however I just while testing the max size so I’m going to try and figure it out. I’m thinking it may be from using two scanners now that I’m looking at my code, this is my first experience with scanners. Thanks in advance!
max.nextInt() <=0 reads from the scanner, but if you do so, you miss storing the value.
you will want something like this:
also. it is pointless to use 2 scanners on system.in. use the same scanner object.
use scanner.hasNextInt() if you want to enter multiple values in the same line