Reads CSV File and IF statement value 0?

This code is supposed to read the csv file, use an array to add all the Axillary (Array[2]) together and find an average.

The only twist is that the IF statement is used because I want to split the data to two different variables depending on the value of (Array[3]) which will be either 1 or 2. and find the averages of them separately.

When i run this code, the output value is 0 for both.

package javainputoutput;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
import java.util.Scanner;

public class JavaInputOutput 
{
public static void main(String[] args) 
{
    int totalOverAxillary = 0;
    int countOverAxillary = 0;
    int totalLessAxillary = 0;
    int countLessAxillary = 0;

    String fileName = "haberman.txt";
    try
    {
        Scanner InputStream = new Scanner(new File(fileName));

        while (InputStream.hasNextLine())
        {
            String line = InputStream.nextLine();
            String[] ary = line.split(",");

            int noPosAxillary = Integer.parseInt(ary[2]);
            int survivalStatus = Integer.parseInt(ary[3]);

            if(survivalStatus == 1)
            {
                totalOverAxillary =+ noPosAxillary;
                countOverAxillary++; 
            }
            else if(survivalStatus == 2)
            {
                totalLessAxillary =+ noPosAxillary;
                countLessAxillary++;
            }
        }

        InputStream.close();

        int aveOverAxillary = totalOverAxillary / countOverAxillary;
        int aveLessAxillary = totalLessAxillary / countLessAxillary;

        System.out.print("The average number of positive axillary nodes "
                        + "for patients that survived 5 years or longer is "
                        +  aveOverAxillary);
        System.out.println();
        System.out.print("The average number of positive axillary nodes "
                        + "for patients that died within 5 years is "
                        + aveLessAxillary);
    }
    catch(FileNotFoundException e)
    {
        System.out.println("Cannot find file " + fileName);
    }
    catch(IOException e)
    {
        System.out.println("Problem with input from file " + fileName);
    }
}

}

Answer

It seems you messed up the += operator. Instead of this:

totalOverAxillary =+ noPosAxillary;

It should be this:

totalOverAxillary += noPosAxillary;

You have the above mistake in two places, make sure to fix both.

The effect of this is that the total values will be equal to the last values, instead of the sums. And when you divide those values by the counts, probably the counts are smaller than the values, and integer division results in zeros.

Leave a Reply

Your email address will not be published. Required fields are marked *