0

Edited because original was marked as duplicate to a question that wasn't related at all, not sure why.

So I am trying to write a try catch to see if the user inputs a value that isn't between 0-4 or isn't an integer. It works well for values outside of 0-4 however, when it catches a non int, say I enter "W" my console is just spammed:

"Please enter the rank, must be 0 - 4

This is not an integer"

over and over again until I force stop the program. I've tried including a throw exception and that just gives me an exception in thread "main" error. How do I get the code to return to try if it catches an error / why is my code spamming console?

Here is my code:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;



public class GroupProjPersonal {

public static void main (String[] args) throws IOException {
    boolean rational = false;
    Scanner s = new Scanner(System.in);
    while (rational == false) {
        try{

            System.out.println("Please enter the rank, must be 0 - 4");
            int rank = s.nextInt();
            if (rank < 0) {
                System.out.println("Rank must be between 0 and 4.");
                rational = false;
            }else {
                if (rank > 4) {
                    System.out.println("Rank must be between 0 and 4.");
                    rational = false;
                }
                else {
                    rational = true;
                }


            }
        }


        catch (Exception e) {
            System.out.println("This is not an integer");
            rational = false;




        }
    }
}
}  
Blake
  • 91
  • 6

0 Answers0