Scanner nextInt() causing endless error inside a loop [duplicate]












14
















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.










share|improve this question















marked as duplicate by Hulk, Stephen C java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

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 have scn.nextLine() in a finally{}? (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
















14
















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.










share|improve this question















marked as duplicate by Hulk, Stephen C java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

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 have scn.nextLine() in a finally{}? (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














14












14








14


2







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.










share|improve this question

















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






share|improve this question















share|improve this question













share|improve this question




share|improve this question








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 java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

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 java
Users with the  java badge can single-handedly close java questions as duplicates and reopen them as needed.

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 have scn.nextLine() in a finally{}? (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





    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 a finally{}? (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












5 Answers
5






active

oldest

votes


















12














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!






share|improve this answer





















  • 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













  • 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



















3














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);





share|improve this answer































    1














    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;
    }
    }





    share|improve this answer





















    • 2





      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











    • 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



















    1














    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:




    1. Scanner receives not an integer.

    2. Exception is thrown.

    3. Continue is encountered.

    4. Check loop condition, which is true, so the loop runs again.

    5. Back to step 1.


    You could retrieve the input as a string and later verify that it was actually a number.






    share|improve this answer































      0














      Quick fix



      try {
      n = scn.nextInt();
      } catch(Exception e) {
      e.printStackTrace();
      scn.nextLine(); // <-- add this to move to the next line
      continue;
      }





      share|improve this answer





















      • 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


















      5 Answers
      5






      active

      oldest

      votes








      5 Answers
      5






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      12














      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!






      share|improve this answer





















      • 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













      • 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
















      12














      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!






      share|improve this answer





















      • 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













      • 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














      12












      12








      12







      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!






      share|improve this answer















      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!







      share|improve this answer














      share|improve this answer



      share|improve this answer








      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 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














      • 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













      • 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













      3














      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);





      share|improve this answer




























        3














        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);





        share|improve this answer


























          3












          3








          3







          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);





          share|improve this answer













          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);






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 22 at 10:02









          Joakim DanielsonJoakim Danielson

          9,6933725




          9,6933725























              1














              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;
              }
              }





              share|improve this answer





















              • 2





                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











              • 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
















              1














              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;
              }
              }





              share|improve this answer





















              • 2





                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











              • 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














              1












              1








              1







              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;
              }
              }





              share|improve this answer















              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;
              }
              }






              share|improve this answer














              share|improve this answer



              share|improve this answer








              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 calling parseInt 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





                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











              • 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











              1














              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:




              1. Scanner receives not an integer.

              2. Exception is thrown.

              3. Continue is encountered.

              4. Check loop condition, which is true, so the loop runs again.

              5. Back to step 1.


              You could retrieve the input as a string and later verify that it was actually a number.






              share|improve this answer




























                1














                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:




                1. Scanner receives not an integer.

                2. Exception is thrown.

                3. Continue is encountered.

                4. Check loop condition, which is true, so the loop runs again.

                5. Back to step 1.


                You could retrieve the input as a string and later verify that it was actually a number.






                share|improve this answer


























                  1












                  1








                  1







                  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:




                  1. Scanner receives not an integer.

                  2. Exception is thrown.

                  3. Continue is encountered.

                  4. Check loop condition, which is true, so the loop runs again.

                  5. Back to step 1.


                  You could retrieve the input as a string and later verify that it was actually a number.






                  share|improve this answer













                  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:




                  1. Scanner receives not an integer.

                  2. Exception is thrown.

                  3. Continue is encountered.

                  4. Check loop condition, which is true, so the loop runs again.

                  5. Back to step 1.


                  You could retrieve the input as a string and later verify that it was actually a number.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Jan 22 at 13:26









                  TeunTeun

                  946




                  946























                      0














                      Quick fix



                      try {
                      n = scn.nextInt();
                      } catch(Exception e) {
                      e.printStackTrace();
                      scn.nextLine(); // <-- add this to move to the next line
                      continue;
                      }





                      share|improve this answer





















                      • 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
















                      0














                      Quick fix



                      try {
                      n = scn.nextInt();
                      } catch(Exception e) {
                      e.printStackTrace();
                      scn.nextLine(); // <-- add this to move to the next line
                      continue;
                      }





                      share|improve this answer





















                      • 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














                      0












                      0








                      0







                      Quick fix



                      try {
                      n = scn.nextInt();
                      } catch(Exception e) {
                      e.printStackTrace();
                      scn.nextLine(); // <-- add this to move to the next line
                      continue;
                      }





                      share|improve this answer















                      Quick fix



                      try {
                      n = scn.nextInt();
                      } catch(Exception e) {
                      e.printStackTrace();
                      scn.nextLine(); // <-- add this to move to the next line
                      continue;
                      }






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      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














                      • 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



                      Popular posts from this blog

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      Npm cannot find a required file even through it is in the searched directory