gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 13:18:54 26 4
gpt4 key购买 nike

此代码应该读取 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);
}
}

}

最佳答案

看来您搞乱了 += 运算符。而不是这个:

totalOverAxillary =+ noPosAxillary;

应该是这样的:

totalOverAxillary += noPosAxillary;

您在两个地方出现了上述错误,请确保修复这两个地方。

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

关于java - 读取 CSV 文件和 IF 语句值 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33292323/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com