Why do I get unlimited number of errors












9















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









New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 3





    try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)

    – Stultuske
    1 hour ago











  • try putting break after e.printStackTrace() if you want to break after any exception.

    – Akash
    1 hour ago











  • Possible duplicate of Scanner is skipping nextLine() after using next() or nextFoo()?

    – Sofo Gial
    59 mins ago











  • @Stultuske, wouldn't it work to have scn.nextLine() in a finally{}? (not saying it's a good solution)

    – Joakim Danielson
    46 mins ago













  • @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
    43 mins ago
















9















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









New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 3





    try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)

    – Stultuske
    1 hour ago











  • try putting break after e.printStackTrace() if you want to break after any exception.

    – Akash
    1 hour ago











  • Possible duplicate of Scanner is skipping nextLine() after using next() or nextFoo()?

    – Sofo Gial
    59 mins ago











  • @Stultuske, wouldn't it work to have scn.nextLine() in a finally{}? (not saying it's a good solution)

    – Joakim Danielson
    46 mins ago













  • @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
    43 mins ago














9












9








9


1






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









New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












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






share|improve this question









New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited 29 mins ago









Nikolas

13.3k53368




13.3k53368






New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 1 hour ago









sam smithsam smith

462




462




New contributor




sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






sam smith is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 3





    try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)

    – Stultuske
    1 hour ago











  • try putting break after e.printStackTrace() if you want to break after any exception.

    – Akash
    1 hour ago











  • Possible duplicate of Scanner is skipping nextLine() after using next() or nextFoo()?

    – Sofo Gial
    59 mins ago











  • @Stultuske, wouldn't it work to have scn.nextLine() in a finally{}? (not saying it's a good solution)

    – Joakim Danielson
    46 mins ago













  • @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
    43 mins ago














  • 3





    try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)

    – Stultuske
    1 hour ago











  • try putting break after e.printStackTrace() if you want to break after any exception.

    – Akash
    1 hour ago











  • Possible duplicate of Scanner is skipping nextLine() after using next() or nextFoo()?

    – Sofo Gial
    59 mins ago











  • @Stultuske, wouldn't it work to have scn.nextLine() in a finally{}? (not saying it's a good solution)

    – Joakim Danielson
    46 mins ago













  • @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
    43 mins ago








3




3





try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)

– Stultuske
1 hour ago





try adding a scm.nextLine(); after your scm.nextInt(); call (in your catch as well)

– Stultuske
1 hour ago













try putting break after e.printStackTrace() if you want to break after any exception.

– Akash
1 hour ago





try putting break after e.printStackTrace() if you want to break after any exception.

– Akash
1 hour ago













Possible duplicate of Scanner is skipping nextLine() after using next() or nextFoo()?

– Sofo Gial
59 mins ago





Possible duplicate of Scanner is skipping nextLine() after using next() or nextFoo()?

– Sofo Gial
59 mins ago













@Stultuske, wouldn't it work to have scn.nextLine() in a finally{}? (not saying it's a good solution)

– Joakim Danielson
46 mins ago







@Stultuske, wouldn't it work to have scn.nextLine() in a finally{}? (not saying it's a good solution)

– Joakim Danielson
46 mins ago















@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
43 mins ago





@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
43 mins ago












4 Answers
4






active

oldest

votes


















2














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 (or remains). 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














    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































      0














      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





















      • 1





        This solutions means you are calling parseInt twice

        – Joakim Danielson
        14 mins ago













      • Only in happy case

        – abhilash_goyal
        9 mins ago











      • Benefit it serves is modularity of logic

        – abhilash_goyal
        5 mins ago



















      0














      Quick fix



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


      Correct way to implement it. Not rely on catch exceptions.



      My approach looks not very small like yours, but I avoid catching exceptions in it.



      private static final IntSupplier getIntegerNumber = new IntSupplier() {
      private final Predicate<String> isIntegerString = str -> {
      str = str == null ? null : str.trim();
      str = str == null || str.isEmpty() ? null : str;

      if (str == null)
      return false;

      for (int i = 0; i < str.length(); i++) {
      if (str.charAt(i) == '-') {
      if (i != 0)
      return false;
      } else if (str.charAt(i) < '0' || str.charAt(i) > '9')
      return false;
      }

      return true;
      };

      @Override
      public int getAsInt() {
      try (Scanner scan = new Scanner(System.in)) {
      System.out.print("Enter the number: ");

      while (true) {
      String str = scan.nextLine();

      if (isIntegerString.test(str))
      return Integer.parseInt(str);

      System.out.print("This is not an integer number. Try again: ");
      }
      }
      }
      };




      Demo:



      System.out.println(getIntegerNumber.getAsInt());




      P.S.



      According to What's the best way to check if a String represents an integer in Java? this is the fastest way to check if given string an integer or not.






      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
        48 mins ago











      • @Stultuske ok, fixed without ignore exception.

        – oleg.cherednik
        37 mins ago






      • 1





        it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

        – Stultuske
        35 mins ago






      • 1





        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
        30 mins ago











      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });






      sam smith is a new contributor. Be nice, and check out our Code of Conduct.










      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54305087%2fwhy-do-i-get-unlimited-number-of-errors%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      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 (or remains). 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






























        2














        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 (or remains). 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




























          2












          2








          2







          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 (or remains). 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 (or remains). 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 24 mins ago

























          answered 37 mins ago









          Mohamed Anees AMohamed Anees A

          865418




          865418

























              1














              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














                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












                  1








                  1







                  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 30 mins ago









                  Joakim DanielsonJoakim Danielson

                  7,7693724




                  7,7693724























                      0














                      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





















                      • 1





                        This solutions means you are calling parseInt twice

                        – Joakim Danielson
                        14 mins ago













                      • Only in happy case

                        – abhilash_goyal
                        9 mins ago











                      • Benefit it serves is modularity of logic

                        – abhilash_goyal
                        5 mins ago
















                      0














                      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





















                      • 1





                        This solutions means you are calling parseInt twice

                        – Joakim Danielson
                        14 mins ago













                      • Only in happy case

                        – abhilash_goyal
                        9 mins ago











                      • Benefit it serves is modularity of logic

                        – abhilash_goyal
                        5 mins ago














                      0












                      0








                      0







                      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 20 mins ago









                      Hulk

                      3,25612041




                      3,25612041










                      answered 21 mins ago









                      abhilash_goyalabhilash_goyal

                      3561518




                      3561518








                      • 1





                        This solutions means you are calling parseInt twice

                        – Joakim Danielson
                        14 mins ago













                      • Only in happy case

                        – abhilash_goyal
                        9 mins ago











                      • Benefit it serves is modularity of logic

                        – abhilash_goyal
                        5 mins ago














                      • 1





                        This solutions means you are calling parseInt twice

                        – Joakim Danielson
                        14 mins ago













                      • Only in happy case

                        – abhilash_goyal
                        9 mins ago











                      • Benefit it serves is modularity of logic

                        – abhilash_goyal
                        5 mins ago








                      1




                      1





                      This solutions means you are calling parseInt twice

                      – Joakim Danielson
                      14 mins ago







                      This solutions means you are calling parseInt twice

                      – Joakim Danielson
                      14 mins ago















                      Only in happy case

                      – abhilash_goyal
                      9 mins ago





                      Only in happy case

                      – abhilash_goyal
                      9 mins ago













                      Benefit it serves is modularity of logic

                      – abhilash_goyal
                      5 mins ago





                      Benefit it serves is modularity of logic

                      – abhilash_goyal
                      5 mins ago











                      0














                      Quick fix



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


                      Correct way to implement it. Not rely on catch exceptions.



                      My approach looks not very small like yours, but I avoid catching exceptions in it.



                      private static final IntSupplier getIntegerNumber = new IntSupplier() {
                      private final Predicate<String> isIntegerString = str -> {
                      str = str == null ? null : str.trim();
                      str = str == null || str.isEmpty() ? null : str;

                      if (str == null)
                      return false;

                      for (int i = 0; i < str.length(); i++) {
                      if (str.charAt(i) == '-') {
                      if (i != 0)
                      return false;
                      } else if (str.charAt(i) < '0' || str.charAt(i) > '9')
                      return false;
                      }

                      return true;
                      };

                      @Override
                      public int getAsInt() {
                      try (Scanner scan = new Scanner(System.in)) {
                      System.out.print("Enter the number: ");

                      while (true) {
                      String str = scan.nextLine();

                      if (isIntegerString.test(str))
                      return Integer.parseInt(str);

                      System.out.print("This is not an integer number. Try again: ");
                      }
                      }
                      }
                      };




                      Demo:



                      System.out.println(getIntegerNumber.getAsInt());




                      P.S.



                      According to What's the best way to check if a String represents an integer in Java? this is the fastest way to check if given string an integer or not.






                      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
                        48 mins ago











                      • @Stultuske ok, fixed without ignore exception.

                        – oleg.cherednik
                        37 mins ago






                      • 1





                        it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

                        – Stultuske
                        35 mins ago






                      • 1





                        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
                        30 mins ago
















                      0














                      Quick fix



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


                      Correct way to implement it. Not rely on catch exceptions.



                      My approach looks not very small like yours, but I avoid catching exceptions in it.



                      private static final IntSupplier getIntegerNumber = new IntSupplier() {
                      private final Predicate<String> isIntegerString = str -> {
                      str = str == null ? null : str.trim();
                      str = str == null || str.isEmpty() ? null : str;

                      if (str == null)
                      return false;

                      for (int i = 0; i < str.length(); i++) {
                      if (str.charAt(i) == '-') {
                      if (i != 0)
                      return false;
                      } else if (str.charAt(i) < '0' || str.charAt(i) > '9')
                      return false;
                      }

                      return true;
                      };

                      @Override
                      public int getAsInt() {
                      try (Scanner scan = new Scanner(System.in)) {
                      System.out.print("Enter the number: ");

                      while (true) {
                      String str = scan.nextLine();

                      if (isIntegerString.test(str))
                      return Integer.parseInt(str);

                      System.out.print("This is not an integer number. Try again: ");
                      }
                      }
                      }
                      };




                      Demo:



                      System.out.println(getIntegerNumber.getAsInt());




                      P.S.



                      According to What's the best way to check if a String represents an integer in Java? this is the fastest way to check if given string an integer or not.






                      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
                        48 mins ago











                      • @Stultuske ok, fixed without ignore exception.

                        – oleg.cherednik
                        37 mins ago






                      • 1





                        it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

                        – Stultuske
                        35 mins ago






                      • 1





                        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
                        30 mins ago














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


                      Correct way to implement it. Not rely on catch exceptions.



                      My approach looks not very small like yours, but I avoid catching exceptions in it.



                      private static final IntSupplier getIntegerNumber = new IntSupplier() {
                      private final Predicate<String> isIntegerString = str -> {
                      str = str == null ? null : str.trim();
                      str = str == null || str.isEmpty() ? null : str;

                      if (str == null)
                      return false;

                      for (int i = 0; i < str.length(); i++) {
                      if (str.charAt(i) == '-') {
                      if (i != 0)
                      return false;
                      } else if (str.charAt(i) < '0' || str.charAt(i) > '9')
                      return false;
                      }

                      return true;
                      };

                      @Override
                      public int getAsInt() {
                      try (Scanner scan = new Scanner(System.in)) {
                      System.out.print("Enter the number: ");

                      while (true) {
                      String str = scan.nextLine();

                      if (isIntegerString.test(str))
                      return Integer.parseInt(str);

                      System.out.print("This is not an integer number. Try again: ");
                      }
                      }
                      }
                      };




                      Demo:



                      System.out.println(getIntegerNumber.getAsInt());




                      P.S.



                      According to What's the best way to check if a String represents an integer in Java? this is the fastest way to check if given string an integer or not.






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


                      Correct way to implement it. Not rely on catch exceptions.



                      My approach looks not very small like yours, but I avoid catching exceptions in it.



                      private static final IntSupplier getIntegerNumber = new IntSupplier() {
                      private final Predicate<String> isIntegerString = str -> {
                      str = str == null ? null : str.trim();
                      str = str == null || str.isEmpty() ? null : str;

                      if (str == null)
                      return false;

                      for (int i = 0; i < str.length(); i++) {
                      if (str.charAt(i) == '-') {
                      if (i != 0)
                      return false;
                      } else if (str.charAt(i) < '0' || str.charAt(i) > '9')
                      return false;
                      }

                      return true;
                      };

                      @Override
                      public int getAsInt() {
                      try (Scanner scan = new Scanner(System.in)) {
                      System.out.print("Enter the number: ");

                      while (true) {
                      String str = scan.nextLine();

                      if (isIntegerString.test(str))
                      return Integer.parseInt(str);

                      System.out.print("This is not an integer number. Try again: ");
                      }
                      }
                      }
                      };




                      Demo:



                      System.out.println(getIntegerNumber.getAsInt());




                      P.S.



                      According to What's the best way to check if a String represents an integer in Java? this is the fastest way to check if given string an integer or not.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited 4 mins ago

























                      answered 1 hour ago









                      oleg.cherednikoleg.cherednik

                      6,20121118




                      6,20121118








                      • 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
                        48 mins ago











                      • @Stultuske ok, fixed without ignore exception.

                        – oleg.cherednik
                        37 mins ago






                      • 1





                        it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

                        – Stultuske
                        35 mins ago






                      • 1





                        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
                        30 mins ago














                      • 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
                        48 mins ago











                      • @Stultuske ok, fixed without ignore exception.

                        – oleg.cherednik
                        37 mins ago






                      • 1





                        it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

                        – Stultuske
                        35 mins ago






                      • 1





                        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
                        30 mins ago








                      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
                      48 mins ago





                      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
                      48 mins ago













                      @Stultuske ok, fixed without ignore exception.

                      – oleg.cherednik
                      37 mins ago





                      @Stultuske ok, fixed without ignore exception.

                      – oleg.cherednik
                      37 mins ago




                      1




                      1





                      it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

                      – Stultuske
                      35 mins ago





                      it's a bit overkill to go that far. all that was needed was to add "scm.nextLine();" to the original code

                      – Stultuske
                      35 mins ago




                      1




                      1





                      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
                      30 mins ago





                      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
                      30 mins ago










                      sam smith is a new contributor. Be nice, and check out our Code of Conduct.










                      draft saved

                      draft discarded


















                      sam smith is a new contributor. Be nice, and check out our Code of Conduct.













                      sam smith is a new contributor. Be nice, and check out our Code of Conduct.












                      sam smith is a new contributor. Be nice, and check out our Code of Conduct.
















                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54305087%2fwhy-do-i-get-unlimited-number-of-errors%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Callistus I

                      Tabula Rosettana

                      How to label and detect the document text images