java - How to fix my scanner in error if my .txt file is empty? -
i'm taking in strings file , places them linkedlist. program works fine when .txt file has data in it.
however, when no data in .txt file seems throw error...
exception in thread "main" java.util.nosuchelementexception @ java.util.scanner.throwfor(scanner.java:838) @ java.util.scanner.next(scanner.java:1347) @ task.main.main(main.java:85)
would if/else statement fix this??
here's code i'm using, works if .txt file has data.
//read in task data , place task data in ll string contentcomplete = new scanner(new file("completedata.txt")).usedelimiter("\\z").next(); linenumberreader lnr4 = new linenumberreader(new filereader(new file("completedata.txt"))); lnr4.skip(long.max_value); lnr4.close(); realsize = lnr4.getlinenumber(); sizeofin = ((lnr4.getlinenumber() + 1) / 4); //divide 2 because every 4 lines equal 1 input //-----test number of data entries system.out.println("number of data entries progressdata.txt: " + sizeofin); //-----number of lines system.out.println("number of lines progressdata: " + realsize); //splits userdata.txt input 2 parts string[] completecontent = contentcomplete.split("\n"); //loads taskdata ll //update: changed < sizeofin < realsize , appears loading correctly for(int = 0; < realsize; i++) { task temptask = new task(completecontent[i], completecontent[i+1], completecontent[i+2], completecontent[i+3]); completell.add(temptask); = + 3;
you did not share code considering error message seems did not check if scanner still had tokens in input before asking next token
for purpose should use scanner.hasnext()
method:
hasnext() returns true if scanner has token in input.
so like
while (scanner.hasnext()) { // process here input scanner // example string data = scanner.next(); }
it don't need implement in loop if like:
if (scanner.hasnext()) { // process here.... }
Comments
Post a Comment