Monday, 15 March 2010

java - Read string of numbers from text file and add them together -


I have a .txt content of that file called this output.txt

Image of Notepad Document

I want to read the last number (with the fourth position) from each

And altogether, add them all together. Mainly, I want to know how to get the text in some useful variables.

  import java.io. *; Import java.util. *; Public class printlotpointhold {personal count; Private string id; File in private file; Private scanner input; The name of the private string; Private file outfile; Private PrintWriter Output; Private integer total; Public PrintTotalPointsHeld (string name, string id, string inFilename, string outFilename) throws exceptions, IOException {} Public Zero processFiles () Exception as a variable, IOException {// Store throws every word so we try our calculations later Can (BufferedReader br = New BufferedReader (New FileReader (Infile))) {StringBinder SB = New stringbilder (); String line = br.readLine (); While (line! = Null) {sb.append (line); Sb.append (System.lineSeparator ()); Line = br.readLine (); } String point = sb.toString (); } Output.println ("" + count + "accounts that put together" + total + "points)";); }}  

}

algorithm step (code ) As follows:

1) Open file which you want to read (using BufferedReader )

2) Start to the counter which will store sum (I am long Because your sum can be too large and integer not able to catch a large number of this kind Can )

3) Line by reading line file ( string line = myReader.readLine (getting the next line using); , make sure Doing there is a side by side using the line (line! = Null) { splitting using line as the delimiter , 4 Keep element starts from 0 since each array ( parts [3] ), in which numbers you want to add Are , and Add this number to previous amount

4) Add print to number of accounts (i.e., and sum when no line is read in the file

  import java.io .BufferedReader; Import java.io.fileReader; Import java.util.Arrays; Import java.io.phileNotFoundException; Import java.io.IOException; Import java.io.file; Class myRead {public static zero main (string [] args) filenotfound exception, IOException {long cnt = 0; Long number of oophline = 0; Buffered Reader MyReader = New buffed reader (new filer ("test.txt")); String line = myReader.readLine (); While (line! = Null) {numberOfLines ++; String [] parts = line. Split (""); Cnt = cnt + integer.percent (part [3]); Line = myReader.readLine (); } System.out.println ("" + Oopsline + "accounts that hold" + cnt + "points together.););}}  

OUTPUT: There are 3 accounts that get 2558543 points simultaneously.


No comments:

Post a Comment