0

How can I specify that you request a number from the console until the number is entered?

I declared a Scanner. Like:Scanner s = new Scanner(System.in); Int i =s.nextInt(); Now if i receive(console) a string instead int i will get exception. How can I specify that you request a number from the console until the number is entered?

10th Apr 2021, 9:47 AM
Hamed Taherkhani
Hamed Taherkhani - avatar
6 Réponses
10th Apr 2021, 10:13 AM
Ciro Pellegrino
Ciro Pellegrino - avatar
+ 2
You can use hasNextInt() and next() in a while loop to check the input type and wait if needed: do { System.out.println("Please input a number."); while (!s.hasNextInt()) { System.out.println("That's not a number!"); sc.next(); // get the next input } // save the number input to a variable }
10th Apr 2021, 10:17 AM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 2
questionable, but if it makes you feel better you are right 😉
10th Apr 2021, 1:58 PM
Ciro Pellegrino
Ciro Pellegrino - avatar
0
Cirro Pellegrino Your code which you sent me out, has a problem. n = Integer.parseInt(scanner.next()); It s really working in exception handling. But when i write a number i have to enter that two times. Why????
10th Apr 2021, 5:47 PM
Hamed Taherkhani
Hamed Taherkhani - avatar
0
correct, readability. therefore it is not clear to you that the code requires insertions indefinitely, stopping at the first valid reading to resume the main flow while it is clearer to you with an additional variable to understand its meaning. I guarantee you that you can obtain enormous conditions reduced with the algebra of Bool to sentences with incomprehensible meaning in the name of structured programming. therefore better a return, break or continue instruction which are anyway controlled jumps than the proliferation of Boolean variables in incomprehensible conditions. this is not the case with just one flag, but you know that the appetite comes with eating. if you really want to be a purist then the best solution is that of camel, that is to avoid also the jump produced by the exceptions
10th Apr 2021, 6:53 PM
Ciro Pellegrino
Ciro Pellegrino - avatar
0
I use nextLine. Then without a code that give the problema it's difficultà to say
10th Apr 2021, 6:56 PM
Ciro Pellegrino
Ciro Pellegrino - avatar