1
 int rollnumber;
 do {
     try {
         System.out.println("how many times");
         rollnumber = scanner.nextInt();

         nigh=2;

        if (Integer.toString(rollnumber).equals("q")  )   {
               System.exit(0);
         }   
     } catch (Exception e){
        System.out.println("invalid. re-enter");
        scanner.nextLine()';    
    }
}while (nigh==1);

Basically, I'm trying to make a "q" (quit) option but it just keeps jumping to the catch statement when I press q. Help me make it so that the "scanner.nextInt()" reads the q as the actual quit command.

Trudbert
  • 2,998
  • 12
  • 14
Boy Boy
  • 33
  • 5

4 Answers4

3

You are trying to read an int from the console. If you enter q, nextInt attempts to convert q to an integer, fails with a NumberFormatException and the code jumps to the catch block.

You should read with next or nextLine and convert the input to an int.

Gabriel Negut
  • 12,932
  • 3
  • 34
  • 43
0

You can use this way. Read String not int.You can use nextLine()

Then

rollnumber = scanner.nextLine(); // read next line
if("q".equalsIgnoreCase(rollnumber)) // if it is q then if condition matched
Ruchira Gayan Ranaweera
  • 32,406
  • 16
  • 66
  • 105
0

The problem is that the .nextInt will only take in an actual int. You could use the .next() method instead of the .nextInt() method and then check to see if it is a "q". If it's not, you could then check if it parses to an Int and if not, use the code in the catch block.

String rollnumber;
try {
    System.out.println("how many times");
    rollnumber = scanner.next();

    nigh=2;

    if (rollnumber.equals("q")  )   {
        System.exit(0);
    } else {
        int num = Integer.parseInt(rollnumber);
    }
} catch (Exception e){
    System.out.println("invalid. re-enter");
    scanner.nextLine()';    
}
michaelp
  • 323
  • 5
  • 23
-2

Change your line to

int rollnumber;
nigh = 1; // added
do {  
 try {       
     System.out.println("how many times");
     String response = scanner.nextLine(); // changed

     rollnumber = scanner.nextInt();     
     nigh=2;
    if(if("q".equalsIgnoreCase(response)){){  // changed
       System.exit(0);
     } else {
             rollnumber = scanner.nextInt();     
             nigh=2;
     }
  }
 catch (Exception e){
    System.out.println("invalid. re-enter");
    scanner.nextLine();    
   }     
 }while (nigh==1);
ErstwhileIII
  • 4,691
  • 2
  • 21
  • 36