如何获取数组中的特定值并输出平均值



我很难弄清楚在这种情况下到底需要做什么才能让代码正常工作。我需要输出一个文本文件,其中包含一个名称和每行值列表的平均值,文本文件包含以下内容:

Carol,35.00,67.00,13.00
Steve,14.00,82.00,41.00,66.00
Sharon,56.00,42.00,28.00,70.00
Roy,80.00,105.00,55.00
Beatrice,20.00

在这种情况下,我如何输出每行的平均值?下面的代码是一个更简单的例子,每行只包含一个值,我只是不知道如何修改数组列表或代码以获得我想要的值。

import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class AvgCalc {
public static void main(String[] args) {

File myFile = new File("C:\Users\Byoma\Downloads\Assignment1.txt");

try {

Scanner myScanner = new Scanner(myFile);

while (myScanner.hasNextLine()) {
String line = myScanner.nextLine();

String[] tokens = line.split(",");
String name = tokens[0];
String average = tokens [1];
System.out.println("Name: " + name + ", Average: " + average);
}

myScanner.close();
}

catch (Exception e) {
System.out.println("Error reading file: " + myFile.getAbsolutePath());
}
}
}

假设您为示例列出的每个人都在文本文件中的一行,那么在当前代码中添加一个for循环并更改几行将为您解决此问题。

import java.util.Scanner;
import java.io.File;
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
File myFile = new File("C:\Users\Byoma\Downloads\Assignment1.txt");
try {
Scanner myScanner = new Scanner(myFile);
while (myScanner.hasNextLine()) {
String line = myScanner.nextLine();
String[] tokens = line.split(",");
String name = tokens[0];
double sum = 0; //Initialized a double to sum the values
for (int i = 1; i < tokens.length; i++) {
sum += Double.parseDouble(tokens[i]); //Parse the values in the text document as doubles
}
double average = sum / (tokens.length - 1); //Get the average by dividing the sum by the number of values
System.out.println("Name: " + name + ", Average: " + average);
}
myScanner.close();
}
catch (Exception e) {
System.out.println("Error reading file: " + myFile.getAbsolutePath());
}
}
}

您从元素1开始迭代数组中的元素并累加它们,然后将元素的总和除以元素的数量(请注意,我使用int表示累加和,但如果您的输入不是整数值,并且您不严格需要count变量,则可以使用浮点或双精度(:

public class MyClass {
public static void main(String args[]) {
String[] array = {"Name", "11", "5", "107"};
int accumulated = 0; //this will hold the sum of all the numbers
int count = 0; //we use this to keep track of how many numbers we have
for (int i = 1; i < array.length; i++) {
//add the numbers, we convert them to int since they are strings
accumulated = accumulated + Integer.parseInt(array[i]); 
count++;
}  
System.out.println("Total sum: "+accumulated);
System.out.println("Number of elements: "+count);
float average = accumulated/count;
System.out.println("Average: "+average);
}
}

输出:

Total sum: 123
Number of elements: 3
Average: 41.0

最新更新