Search code examples
javajava-ioparallel-arrays

read from file as parallel arrays in java


This is my code to read from file and display in console

    try
    {
        BufferedReader readFile = new BufferedReader(new FileReader("sales.txt"));
        String line = "";
        while((line = readFile.readLine()) != null)
        {
            String tmp[] = line.split(",");
            year = Integer.parseInt(tmp[0]);
            quarter = tmp[1];
            sales = Integer.parseInt(tmp[2]);
            //System.out.printf("Year: %s\tQuarter: %s\tSales: %d\n",year,quarter,sales);   
        }
        readFile.close();
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    userInput.close();

in my file named "sales.txt" I have this:

2012,Q1,9300

2012,Q2,10225

2012,Q3,12420

2012,Q4,13250

2013,Q1,10500

2013,Q2,10900

2013,Q3,11340

2013,Q4,14600

Now I am stuck on how to calculate average sales for q4 in year 2012 and 2013


Solution

  • //Or read as Arrays from file

    int[] year = new int [lineCount];
            String[] quarter = new String [lineCount];
            int[] sale = new int [lineCount];
    
            Scanner readFile = new Scanner(new File("sales.txt"));
    
            while(readFile.hasNextLine())
            {
                String salesRecords = readFile.nextLine();
                Scanner lineScan = new Scanner(salesRecords);
                lineScan.useDelimiter(",");
                year[i] = lineScan.nextInt();
                quarter[i] = lineScan.next();
                sale[i] = lineScan.nextInt();
                lineScan.close();
                i++;
            }