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?
8 Answers
+ 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
}
+ 2
questionable, but if it makes you feel better you are right
đ
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????
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
0
I use nextLine. Then without a code that give the problema it's difficultĂ to say