读取CSV文件和IF语句值0?

时间:2015-10-22 23:13:17

标签: java arrays csv average

这段代码应该读取csv文件,使用数组将所有Axillary(Array [2])加在一起并找到一个平均值。

唯一的转折是使用了IF语句,因为我想将数据拆分为两个不同的变量,具体取决于(Array [3])的值,它们将是1或2.并分别找到它们的平均值

当我运行此代码时,两者的输出值均为0.

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);
    }
}

}

1 个答案:

答案 0 :(得分:0)

好像你搞砸了+=运营商。而不是:

totalOverAxillary =+ noPosAxillary;

应该是这样的:

totalOverAxillary += noPosAxillary;

你在两个地方犯了上述错误,一定要解决这两个问题。

这样做的结果是总值将等于最后的值,而不是总和。 当你按计数划分这些值时, 可能计数小于值, 和整数除法结果为零。