java - Take values from a text file and put them in a array -
for in program using hard-coded values, want user can use text file , same result.
import java.io.ioexception; import java.io.bufferedreader; import java.io.filereader; import java.io.file; public class a1_12177903 { public static void main(string [] args) throws ioexception { if (args[0] == null) { system.out.println("file not found"); } else { file file = new file(args[0]); filereader fr = new filereader(file); bufferedreader br = new bufferedreader(fr); string line = ""; while (br.ready()) { line += br.readline(); } string[] work = line.split(","); double[] doublearr = new double[work.length]; (int =0; < doublearr.length; i++) { doublearr[i] = double.parsedouble(work[i]); } double maxstartindex=0; double maxendindex=0; double maxsum = 0; double total = 0; double maxstartindexuntilnow = 0; (int currentindex = 0; currentindex < doublearr.length; currentindex++) { double eacharrayitem = doublearr[currentindex]; total += eacharrayitem; if(total > maxsum) { maxsum = total; maxstartindex = maxstartindexuntilnow; maxendindex = currentindex; } if (total < 0) { maxstartindexuntilnow = currentindex; total = 0; } } system.out.println("max sum : "+ maxsum); system.out.println("max start index : "+ maxstartindex); system.out.println("max end index : " +maxendindex); } } }
i've fixed takes in name of text file command line. if has ways improve this, i'll happily accept improvments.
you can java8 streams, assuming each entry has it's own line
double[] doublearr = files.lines(pathtofile) .maptodouble(double::valueof) .toarray();
if using on production systems (rather exercise) worth while create stream inside try resources block. make sure input file closed properly.
try(stream<string> lines = files.lines(path)){ doublearr = stream.maptodouble(double::valueof) .toarray(); }
if have comma separated list, need split them first , use flatmap.
double[] doublearr = files.lines(pathtofile) .flatmap(line->stream.of(line.split(",")) .maptodouble(double::valueof) .toarray();
Comments
Post a Comment