Я не нахожу ничего плохого с вашим кодом, он может просто вести себя немного иначе, чем вы ожидаете. Итак, вот как я это сделаю.
Одно первое: имена классов должны всегда начинаться с заглавной буквы (не ошибка, а скорее конвенции, которая помогает понять код)
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]);
}
}
Это ни решение, ни лучший способ сделай это. Я просто пытаюсь показать вам, как вы можете направлять пользователя и обрабатывать нежелательный вход.
редактировать: в двух словах, эти вещи должны быть рассмотрены:
- не делают никаких предположений о разумности вашего пользователя, он/она может что-нибудь вход:
1 two 2.3 , 4 . @¹"
- быть уверены, вам нужны номера
10
, в противном случае используйте массив другого размера или список (если вы не знаете, сколько цифр вам нужно)
- Возможно, пользователь не хочет вводить столько чисел и хочет выйти ранее (
if(in.next().equalsIgnoreCase("q")
мог трюк)
- Вы принимаете целые числа? даже отрицательные?
- Вы должны принять
long
или даже BigInteger
?
- Что относительно плавающих точек?
- и как вы хотите обработать ошибку?игнорировать его, заменить его значением по умолчанию, выйти из цикла или даже программы?
И вот несколько примеров работает:
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
что 'while' цикл здесь делает? – emotionlessbananas
Использовать отладчик, и вы будете отказываться от того, что случилось – Jens
while loop для получения ввода с консоли @AsteriskNinja – user3797489