I don't find anything wrong with your code, it may just behave a little different than you expect. So here is how I would do it.
One thing first: class names should always start with a capital letter (not an error but rather a convention that helps to understand the code)
public static void main(String[] args) throws IOException{
int[] date = new int[10]; // as mentioned above, a fixed size array will limit you - but if 10 is what you want, then this is what you need
int i = 0;
System.out.println("Please enter " + date.length + " numbers"); // just some output to tell the user that the program has started and what to do next
Scanner in = new Scanner(System.in); // perfect
// if you absolutely want your array filled, check if you reached the end of your input to avoid IndexOutOfBoundsExceptions.
// in.hasNext() will check for ANY input, which makes it easier to handle unwanted user input
while(i < date.length && in.hasNext()){
if(in.hasNextInt()){ // here you check if the input starts with a number. Beware that "1 w 2" is valid too!
date[i] = in.nextInt();
i++;
}else{
// this is to advise the user of an input error
// but more importantly, in.next() will read the invalid input and remove it from the inputstream. Thus your scanner will continue to read the input until it ends
System.out.println("sorry \"" + in.next() + "\" is not a valid number");
}
}
System.out.println("your input:");
for(i = 0; i < date.length; i++){ // you don't need any advanced loops, it is perfectly fine to use indexed loops. Just try to make your break condition more dynamic (like checking the length of the array instead of a constant value)
System.out.println(date[i]);
}
}
This is neither a solution, nor the best way to do it. I am merely trying to show you how you can guide your user and handle unwanted input.
edit: in a nutshell, these things should be considered:
- don't make any assumption on the intelligence of your user, he/she could input anything:
1 two 2.3 , 4 . @¹"
- be sure you want
10
numbers, otherwise either use an array of a different size, or a list (if you don't know how many numbers you need)
- maybe the user doesn't want to input as many numbers and wants to quit earlier (
if(in.next().equalsIgnoreCase("q")
could do the trick )
- do you accept any integers? even negative ones?
- should you accept
long
as well or even BigInteger
?
- what about floating points?
- and how do you want to handle the error? ignore it, replace it with a default value, exit the loop or even the program?
And here are some example runs:
Please enter 10 numbers
1
2
3 4 5 6 7 8 9
10
your input:
1
2
3
4
5
6
7
8
9
10
Please enter 10 numbers
1 2 3 4 5 6 7 8 9 10
your input:
1
2
3
4
5
6
7
8
9
10
Please enter 10 numbers
1 2 3 4 r 5 6 7 8 9 10
sorry "r" is not a valid number
your input:
1
2
3
4
5
6
7
8
9
10
Please enter 10 numbers
1 2 3 4 5 6 7 8 9 10 11
your input:
1
2
3
4
5
6
7
8
9
10