Scanner nextInt() causing endless error inside a loop [duplicate]
This question already has an answer here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
5 answers
The following code output endless errors, when a user entered not a number.
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true){
try {
n = scn.nextInt();
} catch (Exception e) {
e.printStackTrace();
continue;
}
break;
}
I expect that the code wait for new input when user entered not a number.
java java.util.scanner
marked as duplicate by Hulk, Stephen C
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Jan 22 at 13:59
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |
This question already has an answer here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
5 answers
The following code output endless errors, when a user entered not a number.
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true){
try {
n = scn.nextInt();
} catch (Exception e) {
e.printStackTrace();
continue;
}
break;
}
I expect that the code wait for new input when user entered not a number.
java java.util.scanner
marked as duplicate by Hulk, Stephen C
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Jan 22 at 13:59
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
3
try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)
– Stultuske
Jan 22 at 9:31
try putting break after e.printStackTrace() if you want to break after any exception.
– Akash
Jan 22 at 9:32
@Stultuske, wouldn't it work to havescn.nextLine()
in afinally{}
? (not saying it's a good solution)
– Joakim Danielson
Jan 22 at 9:46
1
@JoakimDanielson yes. either in the catch (before the continue; statement, or in a finally should do the trick. But since I didn't see a finally block in the OP's code, I just spotted it in a block he does have.
– Stultuske
Jan 22 at 9:49
Very closely related to stackoverflow.com/questions/1794281/…
– Hulk
Jan 22 at 10:20
add a comment |
This question already has an answer here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
5 answers
The following code output endless errors, when a user entered not a number.
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true){
try {
n = scn.nextInt();
} catch (Exception e) {
e.printStackTrace();
continue;
}
break;
}
I expect that the code wait for new input when user entered not a number.
java java.util.scanner
This question already has an answer here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
5 answers
The following code output endless errors, when a user entered not a number.
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true){
try {
n = scn.nextInt();
} catch (Exception e) {
e.printStackTrace();
continue;
}
break;
}
I expect that the code wait for new input when user entered not a number.
This question already has an answer here:
How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner
5 answers
java java.util.scanner
java java.util.scanner
edited Jan 22 at 14:00


Mohamed Anees A
1,226419
1,226419
asked Jan 22 at 9:29
sam smithsam smith
727
727
marked as duplicate by Hulk, Stephen C
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Jan 22 at 13:59
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Hulk, Stephen C
StackExchange.ready(function() {
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function() {
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function() {
$hover.showInfoMessage('', {
messageElement: $msg.clone().show(),
transient: false,
position: { my: 'bottom left', at: 'top center', offsetTop: -7 },
dismissable: false,
relativeToBody: true
});
},
function() {
StackExchange.helpers.removeMessages();
}
);
});
});
Jan 22 at 13:59
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
3
try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)
– Stultuske
Jan 22 at 9:31
try putting break after e.printStackTrace() if you want to break after any exception.
– Akash
Jan 22 at 9:32
@Stultuske, wouldn't it work to havescn.nextLine()
in afinally{}
? (not saying it's a good solution)
– Joakim Danielson
Jan 22 at 9:46
1
@JoakimDanielson yes. either in the catch (before the continue; statement, or in a finally should do the trick. But since I didn't see a finally block in the OP's code, I just spotted it in a block he does have.
– Stultuske
Jan 22 at 9:49
Very closely related to stackoverflow.com/questions/1794281/…
– Hulk
Jan 22 at 10:20
add a comment |
3
try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)
– Stultuske
Jan 22 at 9:31
try putting break after e.printStackTrace() if you want to break after any exception.
– Akash
Jan 22 at 9:32
@Stultuske, wouldn't it work to havescn.nextLine()
in afinally{}
? (not saying it's a good solution)
– Joakim Danielson
Jan 22 at 9:46
1
@JoakimDanielson yes. either in the catch (before the continue; statement, or in a finally should do the trick. But since I didn't see a finally block in the OP's code, I just spotted it in a block he does have.
– Stultuske
Jan 22 at 9:49
Very closely related to stackoverflow.com/questions/1794281/…
– Hulk
Jan 22 at 10:20
3
3
try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)
– Stultuske
Jan 22 at 9:31
try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)
– Stultuske
Jan 22 at 9:31
try putting break after e.printStackTrace() if you want to break after any exception.
– Akash
Jan 22 at 9:32
try putting break after e.printStackTrace() if you want to break after any exception.
– Akash
Jan 22 at 9:32
@Stultuske, wouldn't it work to have
scn.nextLine()
in a finally{}
? (not saying it's a good solution)– Joakim Danielson
Jan 22 at 9:46
@Stultuske, wouldn't it work to have
scn.nextLine()
in a finally{}
? (not saying it's a good solution)– Joakim Danielson
Jan 22 at 9:46
1
1
@JoakimDanielson yes. either in the catch (before the continue; statement, or in a finally should do the trick. But since I didn't see a finally block in the OP's code, I just spotted it in a block he does have.
– Stultuske
Jan 22 at 9:49
@JoakimDanielson yes. either in the catch (before the continue; statement, or in a finally should do the trick. But since I didn't see a finally block in the OP's code, I just spotted it in a block he does have.
– Stultuske
Jan 22 at 9:49
Very closely related to stackoverflow.com/questions/1794281/…
– Hulk
Jan 22 at 10:20
Very closely related to stackoverflow.com/questions/1794281/…
– Hulk
Jan 22 at 10:20
add a comment |
5 Answers
5
active
oldest
votes
From the javadoc,
When a Scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
In your case, scn.nextInt()
must have thrown InputMismatchException. But the token is not passed (in other words,the input token hangs in there to be passed by Scanner). So on the next iteration of the loop, scn.nextInt() reads the same token again and throws the exception again resulting in an infinite loop.
If you inspect the value of CharBuffer
(HeapCharBuffer?) inside the Scanner object, it still contains the input you have typed the first time and causing this issue. Also, you cannot explicitly clear Scanner's buffer.
Also, beware of resource-leaks!
1
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't openSystem.in
, so you shouldn't close it.
– Andy Turner
Jan 22 at 13:44
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
add a comment |
I would stay away from using nextInt
and instead read input as a string and try to convert it afterwards
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true) {
String input = scn.nextLine();
try {
n = Integer.valueOf(input);
break;
} catch (Exception e) {
System.out.println( input + " is not a valid number. Try again.");
}
}
System.out.println("You entered " + n);
add a comment |
My version:
public class IsNumber {
public static void main(String o) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
String str = null;
do{
str = scn.next();
if(isInteger(str))
break;
}while(true);
System.out.println("Number Entered: " + Integer.parseInt(str));
scn.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(Exception e) {
return false;
}
return true;
}
}
2
This solutions means you are callingparseInt
twice
– Joakim Danielson
Jan 22 at 10:18
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
add a comment |
In your code sample you continue
inside the catch {}
block. This will run the loop again because you run the loop indefinitely. In the loop, the same input is validated as before because the scanner will use the same input again, so it will throw the exception again.
This basically happens:
- Scanner receives not an integer.
- Exception is thrown.
- Continue is encountered.
- Check loop condition, which is true, so the loop runs again.
- Back to step 1.
You could retrieve the input as a string and later verify that it was actually a number.
add a comment |
Quick fix
try {
n = scn.nextInt();
} catch(Exception e) {
e.printStackTrace();
scn.nextLine(); // <-- add this to move to the next line
continue;
}
1
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
3
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
3
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
2
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
add a comment |
5 Answers
5
active
oldest
votes
5 Answers
5
active
oldest
votes
active
oldest
votes
active
oldest
votes
From the javadoc,
When a Scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
In your case, scn.nextInt()
must have thrown InputMismatchException. But the token is not passed (in other words,the input token hangs in there to be passed by Scanner). So on the next iteration of the loop, scn.nextInt() reads the same token again and throws the exception again resulting in an infinite loop.
If you inspect the value of CharBuffer
(HeapCharBuffer?) inside the Scanner object, it still contains the input you have typed the first time and causing this issue. Also, you cannot explicitly clear Scanner's buffer.
Also, beware of resource-leaks!
1
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't openSystem.in
, so you shouldn't close it.
– Andy Turner
Jan 22 at 13:44
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
add a comment |
From the javadoc,
When a Scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
In your case, scn.nextInt()
must have thrown InputMismatchException. But the token is not passed (in other words,the input token hangs in there to be passed by Scanner). So on the next iteration of the loop, scn.nextInt() reads the same token again and throws the exception again resulting in an infinite loop.
If you inspect the value of CharBuffer
(HeapCharBuffer?) inside the Scanner object, it still contains the input you have typed the first time and causing this issue. Also, you cannot explicitly clear Scanner's buffer.
Also, beware of resource-leaks!
1
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't openSystem.in
, so you shouldn't close it.
– Andy Turner
Jan 22 at 13:44
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
add a comment |
From the javadoc,
When a Scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
In your case, scn.nextInt()
must have thrown InputMismatchException. But the token is not passed (in other words,the input token hangs in there to be passed by Scanner). So on the next iteration of the loop, scn.nextInt() reads the same token again and throws the exception again resulting in an infinite loop.
If you inspect the value of CharBuffer
(HeapCharBuffer?) inside the Scanner object, it still contains the input you have typed the first time and causing this issue. Also, you cannot explicitly clear Scanner's buffer.
Also, beware of resource-leaks!
From the javadoc,
When a Scanner throws an InputMismatchException, the scanner will not
pass the token that caused the exception, so that it may be retrieved
or skipped via some other method.
In your case, scn.nextInt()
must have thrown InputMismatchException. But the token is not passed (in other words,the input token hangs in there to be passed by Scanner). So on the next iteration of the loop, scn.nextInt() reads the same token again and throws the exception again resulting in an infinite loop.
If you inspect the value of CharBuffer
(HeapCharBuffer?) inside the Scanner object, it still contains the input you have typed the first time and causing this issue. Also, you cannot explicitly clear Scanner's buffer.
Also, beware of resource-leaks!
edited Jan 22 at 12:02
answered Jan 22 at 9:55


Mohamed Anees AMohamed Anees A
1,226419
1,226419
1
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't openSystem.in
, so you shouldn't close it.
– Andy Turner
Jan 22 at 13:44
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
add a comment |
1
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't openSystem.in
, so you shouldn't close it.
– Andy Turner
Jan 22 at 13:44
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
1
1
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't open
System.in
, so you shouldn't close it.– Andy Turner
Jan 22 at 13:44
"Also, beware of resource-leaks!" There are no resource leaks in this code. You should close any stream that you open, and haven't handed over ownership of; you didn't open
System.in
, so you shouldn't close it.– Andy Turner
Jan 22 at 13:44
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
Yes, in this case it is perfectly safe not to close since we did not open System.in
– Mohamed Anees A
Jan 23 at 16:16
add a comment |
I would stay away from using nextInt
and instead read input as a string and try to convert it afterwards
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true) {
String input = scn.nextLine();
try {
n = Integer.valueOf(input);
break;
} catch (Exception e) {
System.out.println( input + " is not a valid number. Try again.");
}
}
System.out.println("You entered " + n);
add a comment |
I would stay away from using nextInt
and instead read input as a string and try to convert it afterwards
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true) {
String input = scn.nextLine();
try {
n = Integer.valueOf(input);
break;
} catch (Exception e) {
System.out.println( input + " is not a valid number. Try again.");
}
}
System.out.println("You entered " + n);
add a comment |
I would stay away from using nextInt
and instead read input as a string and try to convert it afterwards
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true) {
String input = scn.nextLine();
try {
n = Integer.valueOf(input);
break;
} catch (Exception e) {
System.out.println( input + " is not a valid number. Try again.");
}
}
System.out.println("You entered " + n);
I would stay away from using nextInt
and instead read input as a string and try to convert it afterwards
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
int n = 0;
while(true) {
String input = scn.nextLine();
try {
n = Integer.valueOf(input);
break;
} catch (Exception e) {
System.out.println( input + " is not a valid number. Try again.");
}
}
System.out.println("You entered " + n);
answered Jan 22 at 10:02
Joakim DanielsonJoakim Danielson
9,6933725
9,6933725
add a comment |
add a comment |
My version:
public class IsNumber {
public static void main(String o) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
String str = null;
do{
str = scn.next();
if(isInteger(str))
break;
}while(true);
System.out.println("Number Entered: " + Integer.parseInt(str));
scn.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(Exception e) {
return false;
}
return true;
}
}
2
This solutions means you are callingparseInt
twice
– Joakim Danielson
Jan 22 at 10:18
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
add a comment |
My version:
public class IsNumber {
public static void main(String o) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
String str = null;
do{
str = scn.next();
if(isInteger(str))
break;
}while(true);
System.out.println("Number Entered: " + Integer.parseInt(str));
scn.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(Exception e) {
return false;
}
return true;
}
}
2
This solutions means you are callingparseInt
twice
– Joakim Danielson
Jan 22 at 10:18
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
add a comment |
My version:
public class IsNumber {
public static void main(String o) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
String str = null;
do{
str = scn.next();
if(isInteger(str))
break;
}while(true);
System.out.println("Number Entered: " + Integer.parseInt(str));
scn.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(Exception e) {
return false;
}
return true;
}
}
My version:
public class IsNumber {
public static void main(String o) {
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number: ");
String str = null;
do{
str = scn.next();
if(isInteger(str))
break;
}while(true);
System.out.println("Number Entered: " + Integer.parseInt(str));
scn.close();
}
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(Exception e) {
return false;
}
return true;
}
}
edited Jan 22 at 10:12
Hulk
3,42312042
3,42312042
answered Jan 22 at 10:11
abhilash_goyalabhilash_goyal
3661618
3661618
2
This solutions means you are callingparseInt
twice
– Joakim Danielson
Jan 22 at 10:18
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
add a comment |
2
This solutions means you are callingparseInt
twice
– Joakim Danielson
Jan 22 at 10:18
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
2
2
This solutions means you are calling
parseInt
twice– Joakim Danielson
Jan 22 at 10:18
This solutions means you are calling
parseInt
twice– Joakim Danielson
Jan 22 at 10:18
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Only in happy case
– abhilash_goyal
Jan 22 at 10:23
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Benefit it serves is modularity of logic
– abhilash_goyal
Jan 22 at 10:28
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
Could alternatively return Optional<Integer> and avoid the duplicate call.
– Ben R.
Jan 22 at 11:41
add a comment |
In your code sample you continue
inside the catch {}
block. This will run the loop again because you run the loop indefinitely. In the loop, the same input is validated as before because the scanner will use the same input again, so it will throw the exception again.
This basically happens:
- Scanner receives not an integer.
- Exception is thrown.
- Continue is encountered.
- Check loop condition, which is true, so the loop runs again.
- Back to step 1.
You could retrieve the input as a string and later verify that it was actually a number.
add a comment |
In your code sample you continue
inside the catch {}
block. This will run the loop again because you run the loop indefinitely. In the loop, the same input is validated as before because the scanner will use the same input again, so it will throw the exception again.
This basically happens:
- Scanner receives not an integer.
- Exception is thrown.
- Continue is encountered.
- Check loop condition, which is true, so the loop runs again.
- Back to step 1.
You could retrieve the input as a string and later verify that it was actually a number.
add a comment |
In your code sample you continue
inside the catch {}
block. This will run the loop again because you run the loop indefinitely. In the loop, the same input is validated as before because the scanner will use the same input again, so it will throw the exception again.
This basically happens:
- Scanner receives not an integer.
- Exception is thrown.
- Continue is encountered.
- Check loop condition, which is true, so the loop runs again.
- Back to step 1.
You could retrieve the input as a string and later verify that it was actually a number.
In your code sample you continue
inside the catch {}
block. This will run the loop again because you run the loop indefinitely. In the loop, the same input is validated as before because the scanner will use the same input again, so it will throw the exception again.
This basically happens:
- Scanner receives not an integer.
- Exception is thrown.
- Continue is encountered.
- Check loop condition, which is true, so the loop runs again.
- Back to step 1.
You could retrieve the input as a string and later verify that it was actually a number.
answered Jan 22 at 13:26
TeunTeun
946
946
add a comment |
add a comment |
Quick fix
try {
n = scn.nextInt();
} catch(Exception e) {
e.printStackTrace();
scn.nextLine(); // <-- add this to move to the next line
continue;
}
1
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
3
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
3
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
2
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
add a comment |
Quick fix
try {
n = scn.nextInt();
} catch(Exception e) {
e.printStackTrace();
scn.nextLine(); // <-- add this to move to the next line
continue;
}
1
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
3
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
3
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
2
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
add a comment |
Quick fix
try {
n = scn.nextInt();
} catch(Exception e) {
e.printStackTrace();
scn.nextLine(); // <-- add this to move to the next line
continue;
}
Quick fix
try {
n = scn.nextInt();
} catch(Exception e) {
e.printStackTrace();
scn.nextLine(); // <-- add this to move to the next line
continue;
}
edited Jan 22 at 10:57
answered Jan 22 at 9:32
oleg.cherednikoleg.cherednik
7,12021119
7,12021119
1
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
3
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
3
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
2
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
add a comment |
1
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
3
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
3
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
2
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
1
1
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
only problem with your code, is that when applied to the wrong scenario, it has the same problem. hiding Exceptions is never a good thing.
– Stultuske
Jan 22 at 9:44
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
@Stultuske ok, fixed without ignore exception.
– oleg.cherednik
Jan 22 at 9:55
3
3
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code
– Stultuske
Jan 22 at 9:57
3
3
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
This does not answer the question at all. OP asked why he was getting exceptions with his code and you ended up rewriting it completely using concepts that OP definitely does not know.
– nbokmans
Jan 22 at 10:02
2
2
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
This is overly complicated. Checking for an exception is way easier and more robust. Now it can happen that isIntegerString returns true while parseInt still throws an exception in case of a too big integer or if you have a bug in isIntegerString.
– user42723
Jan 22 at 10:56
add a comment |
3
try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)
– Stultuske
Jan 22 at 9:31
try putting break after e.printStackTrace() if you want to break after any exception.
– Akash
Jan 22 at 9:32
@Stultuske, wouldn't it work to have
scn.nextLine()
in afinally{}
? (not saying it's a good solution)– Joakim Danielson
Jan 22 at 9:46
1
@JoakimDanielson yes. either in the catch (before the continue; statement, or in a finally should do the trick. But since I didn't see a finally block in the OP's code, I just spotted it in a block he does have.
– Stultuske
Jan 22 at 9:49
Very closely related to stackoverflow.com/questions/1794281/…
– Hulk
Jan 22 at 10:20