i have task read text file several lines, after need count every character's unicode value, sum of "hello" 532 , "how you" 1059 , on, every string begins on new line in .txt document , far good. every line need print own value, , way code works, adds every line's value , cant head around way stop when end of lxtine comes looks like: *read line *count char values *add *print them *start on next line, ,
import java.io.bufferedreader; import java.io.filereader; import java.io.ioexception; import java.io.reader; import java.lang.string; import java.util.arrays; public class sumlines { public static void main(string[] args) { string filepath = "/home/lines.txt"; string readline; int sum = 0; try (bufferedreader bufferedreader = new bufferedreader(new filereader(filepath))) { while ((readline = bufferedreader.readline()) != null) { char[] array = new char[readline.length()]; system.out.println(readline); (int = 0; < readline.length(); i++) { arrays.fill(array, readline.trim().charat(i)); sum += (int) array[i]; system.out.print(sum + " "); } } } catch (ioexception e) { system.out.println("error.\n invalid or missing file."); e.printstacktrace(); } system.out.println("\n*** final " + sum); } }
if understood correctly, input:
hello how
you output:
hello 532 how 1059 *** final 1591
for this, need make modifications code:
- in addition calculating sum of characters values per line, keep sum of total of lines
- for each input line, print line followed sum of character values
- you don't need array @ all
- it's better trim input line once, instead of every character
like this:
int total = 0; try (bufferedreader bufferedreader = new bufferedreader(new filereader(filepath))) { string readline; while ((readline = bufferedreader.readline()) != null) { string trimmed = readline.trim(); int sum = 0; (int = 0; < trimmed.length(); i++) { sum += (int) trimmed.charat(i); } system.out.println(readline + " " + sum); total += sum; } } catch (ioexception e) { system.out.println("error.\n invalid or missing file."); e.printstacktrace(); } system.out.println("\n*** final " + total);
Comments
Post a Comment