-3

I have a try-catch that is meant to catch anything that is not an integer. When I enter a non integer (e.g. 5.6) it tells me only integers are allowed and lets me try again (as it should). But if I enter a non-integer again it doesn't say anything and will keep taking inputs, leaving output blank.

if (choicesObjects == b) {
    System.out.println("TEST 2");            
    System.out.println("Object: Right triangle");
    System.out.println("\nEnter length of Right triangle: ");

    int lengthOfTriangle = 0;  
    try {                 
        lengthOfTriangle = input.nextInt();         
    } catch(InputMismatchException e) {        
        System.out.println("\nError: user input must be an integer greater than 0.\n");
        System.out.println("Object: Right triangle");
        System.out.println("\nEnter length of Right triangle: ");
        input.next();                
    }
    //method stuff
}
xlm
  • 6,854
  • 14
  • 53
  • 55
anyset
  • 43
  • 2
  • 7

4 Answers4

4

The try/catch statement is not a loop. It will always be executed once.

Of course, if there is a loop inside the try block, that block will keep executing until terminated. But such a loop requires an explicit command like while or for to be used.

Apparently what happens when entering a non-integer value (e.g., 5.6), is that the nextInt() statement throws an Exception and goes to the catch block. A better explanation can be given if the full code of the method is provided.

PNS
  • 19,295
  • 32
  • 96
  • 143
3

For this you could define a function, something like this should work

private int getNextInt(Scanner input) {
    boolean isInt = false;
    int userInput;
    while(!isInt) {
        try {
            userInput = Integer.valueOf(input.next());
            isInt = true;
        } catch(NumberFormatException e) {
            // Do nothing with the exception
        }
    }
    return userInput;
}

This should run until an input given was an int and then return said int

fotoply
  • 3
  • 2
Mikenno
  • 294
  • 3
  • 9
  • 1
    you have to consume the invalid token in the catch too, otherwise it is stuck in an infinite loop. See [here](http://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-using-scanner) – dumbPotato21 Mar 20 '17 at 23:50
  • @Mikenno You got compensated ... and honestly: deleting not so good answers is great practice. p1 just for doing that ! – GhostCat Mar 23 '17 at 20:01
  • @GhostCat thanks, i believe that good ansswers are the most important thing :) – Mikenno Mar 23 '17 at 20:02
  • True. At some point you realize that reputation and badges matter too; but that is a rabbit hole, and kills your social life. So avoid going down that path ;-) – GhostCat Mar 23 '17 at 20:03
1

You can update your code to something like this -

    Scanner in = new Scanner(System.in);
    int num = 0;
    while(true) {
        try{
            num = in.nextInt();
            break;
        }catch(Exception e){
            //print statements
            System.out.println("Try again");
        }
    }
    System.out.println("Done");
Devendra Lattu
  • 2,732
  • 2
  • 18
  • 27
  • did you test this ? Because this doesn't work for me [here](https://ideone.com/hHktSE). Just gets stuck in an infinite loop, printing `Try again` – dumbPotato21 Mar 20 '17 at 23:35
  • Yes, @Shashwat. I confirmed the execution of the above code. – Devendra Lattu Mar 20 '17 at 23:36
  • check the link I just gave – dumbPotato21 Mar 20 '17 at 23:36
  • So, sometimes there are carriage returns (\n) being executed and which is resulting in this condition. Try implementing it on your IDE instead :) Meanwhile, I am editing your code and trying to fix it... – Devendra Lattu Mar 20 '17 at 23:40
  • I don't think that's the issue. The Problem is you have to consume the invalid token in the `catch`. See [here](http://stackoverflow.com/questions/3572160/how-to-handle-infinite-loop-caused-by-invalid-input-using-scanner) – dumbPotato21 Mar 20 '17 at 23:48
  • That is an excellent reference. I never thought about consuming the invalid tokens. Thanks for correcting me here. – Devendra Lattu Mar 20 '17 at 23:54
  • 1
    "I never thought about consuming the invalid tokens" If there were no invalid tokens, there'd be no need for the loop... – Andy Turner Mar 21 '17 at 00:09
1

something like this

Boolean check = true;

while (check) { if choicesObjects == b {

enter code here` System.out.println("TEST 2"); System.out.println("Object: Right triangle"); System.out.println("\nEnter length of Right triangle: ");

            int lengthOfTriangle = 0;

            try {

            lengthOfTriangle = input.nextInt();


            } catch(InputMismatchException e) {

                System.out.println("\nError: user input must be an integer greater than 0.\n");
                check = false;

System.out.println("Object: Right triangle");System.out.println("\nEnter length of Right triangle:"); input.next();

            }
               //method stuff
          }
        } 

`

demopix
  • 159
  • 6