arrays - How to read values in a text document and then make then parse them to ints in JAVA -



arrays - How to read values in a text document and then make then parse them to ints in JAVA -

i'm trying read lines of text document , take average of numbers. plan first read info in text file. split string string array, parse each index int array. code point of reading document.

my text doc:

3, 7, 24, 66,

10, 50, 20, 40,

100, 20, 69, 911,

import java.io.bufferedreader; import java.io.file; import java.io.filenotfoundexception; import java.io.filereader; import java.io.ioexception; public class testing { public static void main(string[] args) throws ioexception { seek { string path; path = "testnumbers.txt"; file f = new file(path); filereader re = new filereader(f); bufferedreader in = new bufferedreader(re); string line = ""; string store = ""; while((line = in.readline()) != null) { store = store + line; } system.out.println(store); } grab (filenotfoundexception e) { e.printstacktrace(); } } }

output: 3, 7, 24, 66, 10, 50, 20, 40,100, 20, 69, 911,

in perfect world want values separated either "," or " ".

i tried modifying store = store + line + " "; failed because iterate space when readline() on blank line.

i can traverse arrays parse int , take average, setting string split stumping me. tried string.replace(), string.trim(), , 1 failed me. isn't homework, i'm in highschool ap cs , own independent study.

thanks help, showed plenty of ways it. ended going .replace, , made " " "". split via commas. want seek out regex thing though. again.

scary wombat mentioned how handle blank lines.

you .replace swap " " chars "," chars. if expect both ", " in cases .replace "," first. these tricks.

you @ string.split(regex) since regex pattern "[, ]+" take number of spaces and/or commas between numbers separator.

here's quick demo tested (skipping file input, since seem have figured out):

public class tmp { public static void main(string[] args) { string input = "1,2, 3, 4\n5, 6, 7\n\n,8"; //what read file input = input.replace("\n"," "); //simulate removing newlines, ignore string[] items = input.split("[, ]+"); //regex split for(string 1 : items) { system.out.println(one); } } }

java arrays string parsing object

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

json - Hibernate and Jackson (java.lang.IllegalStateException: Cannot call sendError() after the response has been committed) -

C++ 11 "class" keyword -