当前正在处理作业,我需要读取一个数字文件,并显示数字的总数,偶数的总数,奇数的总数以及这三者的平均值。我目前正在努力寻找偶数和奇数的平均值。我必须显示偶数和奇数的平均值。我通过使用parseInt将读入的数字字符串转换为ints来找到总平均值,因此我可以计算平均值,但是当我尝试对偶数和奇数进行相同操作时,我无法使它起作用
这是我当前的代码:
public class Homework1 {
public static void main(String[] args) throws IOException {
// reads file in
File num = new File("numbers.txt");
Scanner inputFile = new Scanner(num);
// creates rounding object
DecimalFormat rounding = new DecimalFormat("#.##");
// neccesary variables
int count = 0;
double numbers =0;
int evenNum =0;
int oddNum =0;
double avg;
double evenAvg;
double oddAvg;
double sum = 0.0;
double evenSum = 0.0;
double oddSum = 0.0;
// reads in numbers file until last line is read
while(inputFile.hasNext())
{
String nums = inputFile.nextLine();
// converts string to ints so numbers can be added
sum += Integer.parseInt(nums);
// converts string to ints to so odd/even nums can be distinguished
numbers = Integer.parseInt(nums);
// updates total number count
count++;
// separates evens from odds
if(numbers % 2 == 0)
{
evenNum++;
evenSum += Integer.parseInt(nums);
}
else
oddNum++;
evenSum += Integer.parseInt(nums);
}
// calculates total num average
avg = sum/count;
// evenAvg =
// oddAvg =
// output of credentials and results
System.out.println("There are " +count+ " numbers in the file"+"\n");
System.out.println("There are " +evenNum+ " even numbers"+"\n");
System.out.println("There are " +oddNum+ " odd numbers"+"\n");
System.out.println("The total average value is " +rounding.format(avg)+"\n");
System.out.println("The odd number average is " +rounding.format(evenAvg)+"\n");
System.out.println("The even number average is " +rounding.format(oddAvg)+"\n");
}
输出:
There are 982 numbers in the file
There are 474 even numbers
There are 508 odd numbers
The total average value is 50362.43
答案 0 :(得分:1)
好的,所以我更正了if / else语句并添加了方括号,这解决了我遇到的问题
oddNum++;
oddSum += Integer.parseInt(nums);