java - Why doesn't my error check work? -


what did made error check loops through everytime invalid filename entered user:

    public static scanner readfile(string filename){     scanner stdin = new scanner(system.in);     file input = new file(filename);     scanner sc = null;     {         try {             sc = new scanner(input);     }         catch(filenotfoundexception e) {             system.out.println("filename not valid. please try again:");             filename = stdin.nextline();     } } while (!new file(filename).exists());              return sc;     } 

i have enough method reads file , puts data array:

public static co2data[] readdata(string filename){ file input = new file(filename);     scanner sc = null;     try{         sc = new scanner(input);     }     catch(filenotfoundexception e){         system.out.println("filename not valid");         system.exit(-1);     } string info = sc.nextline(); int total = sc.nextint(); co2data[] arr = new co2data[total]; for(int i=0; i<10;i++){     arr[i] = new co2data();     } for(int i=0; i<10;i++){      arr[i].setcountry(sc.next());     arr[i].settotalco2(sc.nextdouble());     arr[i].setroadco2(sc.nextdouble());     arr[i].setco2perperson(sc.nextdouble());     arr[i].setcarsperperson(sc.nextint());     } return arr; } 

the problem if type invalid filename first , valid name program says file invalid if type valid filename first program works fine. how come typing valid filename first works fine typing invalid name , valid name makes program give me error message.

well lets walk through full scenario:

if type invalid filename code move catch block, waiting type in new filename line

filename = stdin.nextline();

you type in valid filename , variable filename gets reset new filename (good far)

then move on while block, check if file exists (which does!) good, move return statement (which holds issue)

in return statement return scanner holding previous invalid filename. need remake scanner new file before return it.

i edit while loop read

public static scanner readfile(string filename){ scanner stdin = new scanner(system.in); file input = new file(filename); scanner sc = null; {     try {         input = new file(filename);         sc = new scanner(input);     }catch(filenotfoundexception e) {         system.out.println("filename not valid. please try again:");         filename = stdin.nextline();     } } while (!input.exists());     return sc; } 

this way create new file class after receive valid input , return new scanner holding new input


Comments

Popular posts from this blog

python - mat is not a numerical tuple : openCV error -

c# - MSAA finds controls UI Automation doesn't -

wordpress - .htaccess: RewriteRule: bad flag delimiters -