java - Cannot Figure out how to catch InputMismatchException -


so here current code catching inputmismatchexception error

int weapon = 0    boolean selection = true;    while(selection) {     try {       system.out.println("pick number 1, 2, or 3.");       weapon = scan.nextint();        selection = false;     } catch(inputmismatchexception e) {         system.out.println("choose 1,2,3");         weapon = scan.nextint();       }    } 

i'm trying make sure int entered , not else. scanner class been implemented , 'scan' act me.

thanks efforts help!

try this:

int weapon = 0;    do{        system.out.println("pick number 1, 2, or 3.");        if(scan.hasnextint()){            weapon = scan.nextint();            break;        }else{            system.out.println("enter integer only");            scan.nextline();        }    }while(true); 

this make sure integer , keep asking until gets it.


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 -