5

I am creating a small algorithm and this is a part of it.

If the user enters non integer values, I want to output a message and let the user enter a number again:

boolean wenttocatch;

do 
{
    try 
    {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);

I am getting a never ending loop and I can't figure out why.

How can I identify if the user enters some non integer number?
If the user enters a non integer number, how can I ask the user to enter again?

Update
When I am printing the exception I get 'InputMismatchException', what should I do?

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
pavithra
  • 316
  • 1
  • 5
  • 19

8 Answers8

6

The Scanner does not advance until the item is being read. This is mentioned in Scanner JavaDoc. Hence, you may just read the value off using .next() method or check if hasInt() before reading int value.

boolean wenttocatch;
int number_of_rigons = 0;
Scanner sc = new Scanner(System.in);

do {
    try {
        wenttocatch = false;
        number_of_rigons = sc.nextInt(); // sc is an object of scanner class
    } catch (InputMismatchException e) {
        sc.next();
        wenttocatch = true;
        System.out.println("xx");
    }
} while (wenttocatch == true);
Ola Ström
  • 4,136
  • 5
  • 22
  • 41
James Jithin
  • 10,183
  • 5
  • 36
  • 51
  • Don't forget to clear the input buffer after a valid input. You need to add: `scannerInput.nextLine();` after the last line of this code. – Ola Ström Mar 25 '20 at 12:09
5

You dont have to do a try catch. This code will do the trick for you :

public static void main(String[] args) {
    boolean wenttocatch = false;
    Scanner scan = new Scanner(System.in);
    int number_of_rigons = 0;
    do{
        System.out.print("Enter a number : ");
        if(scan.hasNextInt()){
            number_of_rigons = scan.nextInt();
            wenttocatch = true;
        }else{
            scan.nextLine();
            System.out.println("Enter a valid Integer value");
        }
    }while(!wenttocatch);
}
Yassine.b
  • 617
  • 5
  • 11
  • Don't forget to clear the input buffer after a valid input. You need to add this code line: `scannerInput.nextLine();` after the while line in the above code. – Ola Ström Mar 25 '20 at 12:10
0

Anytime you get an exception, wenttocatch is set to true and the program will be stuck in an infinite loop. As long as you don't get the exception you'll not get an infinite loop.

Django
  • 135
  • 1
  • 2
  • 16
0

The logic if sc.nextInt() causing the error is this

1) wenttocatch is set to false

2) sc.nextInt() throws error

3) wenttocatch is set to true

4) repeat[because wenttocatch is true]

To solve this set wentocatch=false in catch statement

catch (Exception e) {
               wenttocatch=false;
               System.out.println("xx");
            }

if you are doing more than you show here, use a counter[if your counting or a boolean if you are not], but unless you are doing more, do the first thing above

boolean wenttocatch;
int count = 0;

            do{


             try {
                 wenttocatch=false;
                number_of_rigons=sc.nextInt(); // sc is an object of scanner class 
            } catch (Exception e) {
               count++;
               wenttocatch=true;
               System.out.println("xx");

            }

            }while(wenttocatch==true && count < 1);

Answer Comment:

I think you want to get ints until a user doesn't enter anymore. Depending on your input one way of doing that is this

int number_of_rigons;
while((number_of_rigons = sc.nextInt()) != null){
    //do something
}
applecrusher
  • 5,508
  • 5
  • 39
  • 89
  • well what i want is i want to get an integer until he enters an integer the while loop should run again and again – pavithra Sep 15 '15 at 18:35
  • Not quite sure what you mean. You want to get all the integers a user inputs until they don't input anymore integers? – applecrusher Sep 15 '15 at 18:44
0

you simply can use the hasNext(); method in java, instead of try and catch. The hasNext() is a method of Java Scanner class that returns true if this scanner has another token in its input.

Anton
  • 1
  • 1
0
 String[] stringArray = new String[lines];
   int i = 0;
   try (Scanner sc = new Scanner(file)) {
       while (sc.hasNextLine()) {
           String data=sc.nextLine();
           stringArray[i] = data;

           i++;
       }
   } catch (FileNotFoundException fileNotFoundException) {
       System.err.println("Error opening file.");
       throw new FileNotFoundException();
   } catch (NoSuchElementException e) {
       System.err.println("Error in file record structure");
       throw new NoSuchElementException();
   } catch (Exception e) {
       e.printStackTrace();
   }
  
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 13 '21 at 17:32
0

/*added the scanner declaration inside try im new on programming its worked for me but I don't know if its good practice */ :

    boolean wenttocatch;
    do 
    {
        try 
        {
           
        Scanner sc=new Scanner(System.in);
         wenttocoatch = false;
        number_of_rigons = sc.nextInt(); 
    } 
    catch (Exception e) 
    {
        wenttocatch=true;
        System.out.println("xx");
    }
} while (wenttocatch==true);
-1
....
try {
  ....
} catch (Exception e) {
  sc.next();
  wenttocatch=true;
  System.out.println("xx");
}
Dimang Chou
  • 595
  • 6
  • 9
  • Sorry, glanced at this in new posts review and mistakenly thought "well wenttocatch is still true so it's still going to loop". However this is identical to James Jithin's answer. – Vitruvie Feb 08 '18 at 08:21