java - Using InputMismatchException try/catch block -


i want catch input not int , prompt valid input 3 times. after 3 times, program move on , ask rating. can't seem have try/catch block repeat or catch inputmismatchexception. suggestions?

do {     //prompt rating         try {         system.out.println("enter rating between 0-4 movie of week (enter -1 stop/exit): ");         //capture             rating = response.nextint();         } catch (inputmismatchexception err) {             system.out.println("invalid input. please enter rating 0-4 or enter -1 exit: ");             rating = response.nextint();         } //end catch     } while (rating >= 0); 

you either in loop:

int count = 0; {     //prompt rating         try {         system.out.println("enter rating between 0-4 movie of week (enter -1 stop/exit): ");         //capture             rating = response.nextint();         } catch (inputmismatchexception err) {             system.out.println("invalid input. please enter rating 0-4 or enter -1 exit: ");             count++;         } //end catch     } while (rating >= 0 && count < 3); 

or use nested try/ catch:

do {     //prompt rating         try {         system.out.println("enter rating between 0-4 movie of week (enter -1 stop/exit): ");         //capture             rating = response.nextint();         } catch (inputmismatchexception err) {             system.out.println("invalid input. please enter rating 0-4 or enter -1 exit: ");              try {         system.out.println("enter rating between 0-4 movie of week (enter -1 stop/exit): ");         //capture             rating = response.nextint();         } catch (inputmismatchexception err) {             system.out.println("invalid input. please enter rating 0-4 or enter -1 exit: ");             rating = response.nextint();         } //end catch         } //end catch     } while (rating >= 0); 

personally prefer first method.

i tried code , ran without exception:

public class main {

public static void main(string[] args) throws ioexception {     int count = 0;     int rating = 0;     {         scanner response = new scanner(system.in);         //prompt rating             try {             system.out.println("enter rating between 0-4 movie of week (enter -1 stop/exit): ");             //capture                 rating = response.nextint();              } catch (inputmismatchexception err) {                 system.out.println("invalid input. please enter rating 0-4 or enter -1 exit: ");             } {                 count++;                 system.out.println("rating-->" + rating);             }       } while (rating >= 0 && count < 3);  } 

}


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -