LClarke27
LClarke27

Reputation: 23

Storing Data from File into an Array

So I have a text file with items like look like 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 to create arrays from those values, in which the first values of each line are in an array, the second values of each line are in an array, and so on.

This is all the code I have right now, and I can't seem to figure out how to do 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()];


    }
}

Upvotes: 0

Views: 204

Answers (5)

Juned Ahsan
Juned Ahsan

Reputation: 68715

Here is a sample code to read the values from the file and write into an array. Sample code has logic for int array, you can replicate it for other array types as well.

package sales;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class Sales {

    public static void main (String[] args) throws IOException {

        FileInputStream fstream = new FileInputStream("sales.txt");

        BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
        String strLine;
        while ((strLine = br.readLine()) != null)   {
            String[] tokens = strLine.split(" ");
            int[] transID = convertStringToIntArray(tokens[0]);
            for(int i = 0 ; i < transID.length ; i++ )
                System.out.print(transID[i]);
        }

    }

    /** function to convert a string to integer array
     * @param str
     * @return
     */
    private static int[] convertStringToIntArray(String str)  {
        int intArray[] = new int[str.length()];
        for (int i = 0; i < str.length(); i++) {
            intArray[i] = Character.digit(str.charAt(i), 10);
        }
        return intArray;
    }
}

Upvotes: 0

A4L
A4L

Reputation: 17595

In addition to my comment here are 3 ways how you cant do it

read into single arrays

    int size = 2;

    // first allocate some memory for each of your arrays
    int[] transID = new int[size];
    int[] transCode = new int[size];
    String[] time = new String[size];
    double[] trasAmount = new double[size];

    Scanner reader = new Scanner(new File("sales.txt"));
    // keep track of how many elements you have read
    int i = 0;

    // start reading and continue untill there is no more left to read
    while(reader.hasNext()) {
        // since array size is fixed and you don't know how many line your file will have
        // you have to reallocate your arrays when they have reached their maximum capacity
        if(i == size) {
            // increase capacity by 5
            size += 5;
            // reallocate temp arrays
            int[] tmp1 = new int[size];
            int[] tmp2 = new int[size];
            String[] tmp3 = new String[size];
            double[] tmp4 = new double[size];

            // copy content to new allocated memory
            System.arraycopy(transID, 0, tmp1, 0, transID.length);
            System.arraycopy(transCode, 0, tmp2, 0, transCode.length);
            System.arraycopy(time, 0, tmp3, 0, time.length);
            System.arraycopy(trasAmount, 0, tmp4, 0, trasAmount.length);

            // reference to the new memory by your old old arrays
            transID = tmp1;
            transCode = tmp2;
            time = tmp3;
            trasAmount = tmp4;
        }

        // read
        transID[i] = Integer.parseInt(reader.next());
        transCode[i] = Integer.parseInt(reader.next());
        time[i] = reader.next();
        trasAmount[i] = Double.parseDouble(reader.next());
        // increment for next line
        i++;
    }

    reader.close();

    for(int j = 0; j < i; j++) {
        System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
    }

as you see this is a lot of code.

Better you use lists so get rid of the overhead of reallocation and copying (at leas in your own code)

read into single lists

    // instanciate your lists
    List<Integer> transIDList = new ArrayList<>();
    List<Integer> transCodeList = new ArrayList<>();
    List<String> timeList = new ArrayList<>();
    List<Double> trasAmountList = new ArrayList<>();

    reader = new Scanner(new File("sales.txt"));
    int i = 0;

    while(reader.hasNext()) {
        // read
        transIDList.add(Integer.parseInt(reader.next()));
        transCodeList.add(Integer.parseInt(reader.next()));
        timeList.add(reader.next());
        trasAmountList.add(Double.parseDouble(reader.next()));
        i++;
    }

    reader.close();

    for(int j = 0; j < i; j++) {
        System.out.println("" + j + ": " + transIDList.get(j) + ", " + transCodeList.get(j) + ", " + timeList.get(j) + ", " + trasAmountList.get(j));
    }

You see here how small the code went? But but it still can get better...

A line in the sales.txt file seem to constitute data elements of some entity, why not put them in an object ? for that you may write a class named Trans, some think like this:

class Trans {
    public int transID;
    public int transCode;
    public String time;
    public double trasAmount;
    @Override
    public String toString() {
        return transID + ", " + transCode + ", " + time + ", " + trasAmount;
    }
}

Then you can use this class to hold the data you read from your file and put each object of that class in a list.

reading into a list of objects

    reader = new Scanner(new File("sales.txt"));
    List<Trans> transList = new ArrayList<>();  
    int i = 0;

    while(reader.hasNext()) {
        Trans trans = new Trans();
        trans.transID = Integer.parseInt(reader.next());
        trans.transCode = Integer.parseInt(reader.next());
        trans.time = reader.next();
        trans.trasAmount = Double.parseDouble(reader.next());
        transList.add(trans);
        i++;
    }

    reader.close();

    for(Trans trans : transList) {
        System.out.println("" + i++ + ": " + trans);
    }

Output of all 3 methods

0: 350279, 1, 11:54, 107.15
1: 350280, 3, 11:55, 81.27
2: 350281, 2, 11:57, 82.11
3: 350282, 0, 11:58, 92.43
4: 350283, 3, 11:59, 86.11

Upvotes: 0

NullPointerException
NullPointerException

Reputation: 3814

Use Array list because Arrays have fixed size and using Arraylist you add the elements dynamically

   Scanner reader = new Scanner(new File("test.txt"));
    List<Integer> transID = new ArrayList<Integer>();
    List<Integer> transCode = new ArrayList<Integer>();
    List<String> time= new ArrayList<String>();
    List<Double> trasAmount = new ArrayList<Double>();

    while(reader.hasNext() )
    {
        transID.add(reader.nextInt());
        transCode.add(reader.nextInt());
        time.add(reader.next());
        trasAmount.add(reader.nextDouble());

    }

    System.out.println(transID.toString());
    System.out.println(transCode.toString());
    System.out.println(time.toString());
    System.out.println(trasAmount.toString());

Output of the above code

transID     [350279, 350280, 350281, 350282, 350283]
transCode   [1, 3, 2, 0, 3]
time        [11:54, 11:55, 11:57, 11:58, 11:59]
trasAmount  [107.15, 81.27, 82.11, 92.43, 86.11]

Upvotes: 1

durron597
durron597

Reputation: 32343

It's difficult to build an array this way, because Arrays have fixed size... you need to know how many elements they have. If you use a List instead, you don't have to worry about knowing the number of elements in advance. Try this (note: there is 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 into Lists. Note: you can just use the lists if you 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 into arrays
    int index = 0;
    for(Integer i : ids) {
        idArray[index++] = i;
    }
    index = 0;
    for(Integer i : codes) {
        codesArray[index++] = i;
    }
    index = 0;
    for(String i : times) {
        timesArray[index++] = i;
    }
    index = 0;
    for(Double i : ids) {
        amountsArray[index++] = i;
    }
}

Upvotes: 1

Jack Straw
Jack Straw

Reputation: 586

You'll need a while loop to check for input. Since not all inputs are integers you might do something like:

while(reader.hasNextLine()){ //checks to make sure there's still a line to be read in the file
    String line=reader.nextLine(); //record that next line
    String[] values=line.split(" "); //split on spaces
    if(values.length==4){
         int val1=Integer.parseInt(values[0]); //parse values
         int val2=Integer.parseInt(values[1]);
         String val3=values[2];
         double val4=Double.parseDouble(values[3]);
         //add these values to your arrays. Might have to "count" the number of lines on a first pass and then run through a second time... I've been using the collections framework for too long to remember exactly how to work with arrays in java when you don't know the size right off the bat.
    }
}

Upvotes: 0

Related Questions