java - how to read a file thats comma‐delimited -
im tring read file list of strings. there 3 lines in file , im trying print them in file output prints first line. 'woman' should not printed. nor should 'man'
public void readfile(string filename) { string gender; string width; string height; string name; string x; string y; try { scanin = new scanner (new file (filename)); this.scanin.usedelimiter(", "); } catch (filenotfoundexception | numberformatexception exception) { exception.getmessage(); } while(this.scanin.hasnext()){ gender = scanin.next(); if(gender.equals("woman")){ width = scanin.next(); height = scanin.next(); x = scanin.next(); y = scanin.next(); name = scanin.next(); system.out.printf("%s %s %s %s %s", width,height,x,y,name); } if(gender.equals("man")){ width = scanin.next(); height = scanin.next(); x = scanin.next(); y = scanin.next(); name = scanin.next(); system.out.printf("%s %s %s %s %s", width,height,x,y,name); } } }
the file looks
man, 20, 15, 55, 90, phil woman, 30, 10, 5, 80, sam man, 320, 170, 10, 90, olie
the output should be
20, 15, 55, 90, phil 30, 10, 5, 80, sam 320, 170, 10, 90, olie
instead output gives me
20, 15, 55, 90, phil woman
the error because when use delimiter ", "
, scanner won't stop when encounters new line.
so, when reads first line, read phil\nwomen
single token. loop messed up.
to fix, can tell delimit on ", |\n"
, delmit on new line characters.
scanin.usedelimiter(", |\n");
note: may want add newline @ end of printf()
statements, or whole output in single line.
Comments
Post a Comment