io - Java text file remove doubles from four column text file -
i have write code take text file, contains integers , doubles, , print doubles in file , integers in one. text file formatted in following way:
double int int int double int int int ... double int int int it saved in "raw.txt" file.
the output should like:
int int int int int int ... int int int this have tried far:
import java.io.*; import java.util.*; public class data { public static void main(string[] args) throws filenotfoundexception { printwriter writer = new printwriter(new file("sorted.txt")); scanner reader = new scanner(new file("raw.txt")); int temp = 0, count = 1; while (reader.hasnext()) { try { temp = reader.nextint(); } catch (inputmismatchexception e) { reader.nextline(); temp = (int) reader.nextdouble(); } writer.print(temp); if (count % 4 == 0) writer.println(); count++; } writer.close(); reader.close(); } } the current code throws inputmismatchexception. appreciated.
inputmismatchexception can thrown because nether integer either double
better read part string , decide
when deciding, throws numberformatexception can catched
in following code there 2 writers separated wanted, looks better code maybe
have corrected writing file. havent tested think if writer.print(temp);, put integers without spaces, useless then.
try code, not tested
import java.io.*; import java.util.*; public class data { public static void main(string[] args) throws filenotfoundexception { printwriter writerint = new printwriter(new file("sortedint.txt")); printwriter writerdou = new printwriter(new file("sorteddou.txt")); scanner reader = new scanner(new file("raw.txt")); int temp = 0, countint = 1, countdou = 1; while (reader.hasnext()) { string next = reader.next(); try{ temp=integer.parseint(next); writerint.print(temp+" "); if (countint % 4 == 0) writerint.println(); countint++; }catch(numberformatexception e){ try{ writerdou.print(double.parsedouble(next)+" "); if (countdou % 4 == 0) writerdou.println(); countdou++; }catch(numberformatexception f){ system.out.println("not number"); } } } writerint.close(); writerdou.close(); reader.close(); } }
Comments
Post a Comment