java - Storing Data from File into an Array -
so have text file items this:
350279 1 11:54 107.15 350280 3 11:55 81.27 350281 2 11:57 82.11 350282 0 11:58 92.43 350283 3 11:59 86.11
i'm trying create arrays values, in first values of each line in array, second values of each line in array, , on.
this code have right now, , can't seem figure out how it.
package sales; import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class sales { public static void main (string[] args) throws filenotfoundexception { scanner reader = new scanner(new file("sales.txt")); int[] transid = new int[reader.nextint()]; int[] transcode = new int[reader.nextint()]; string[] time = new string[reader.next()]; double[] trasamount = new double[reader.hasnextdouble()]; } }
it's difficult build array way, because arrays have fixed size... need know how many elements have. if use list
instead, don't have worry knowing number of elements in advance. try (note: there no error checking here!):
public static void main (string[] args) throws filenotfoundexception { scanner reader = new scanner(new file("sales.txt")); list<integer> ids = new linkedlist<>(); list<integer> codes = new linkedlist<>(); list<string> times = new linkedlist<>(); list<double> amounts = new linkedlist<>(); // load elements lists. note: can use lists if want while(reader.hasnext()) { ids.add(reader.nextint()); codes.add(reader.nextint()); times.add(reader.next()); amounts.add(reader.nextdouble()); } // create arrays int[] idarray = new int[ids.size()]; int[] codesarray = new int[codes.size()]; string[] timesarray = new string[times.size()]; double[] amountsarray = new double[amounts.size()]; // load elements arrays int index = 0; for(integer : ids) { idarray[index++] = i; } index = 0; for(integer : codes) { codesarray[index++] = i; } index = 0; for(string : times) { timesarray[index++] = i; } index = 0; for(double : ids) { amountsarray[index++] = i; } }
Comments
Post a Comment