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

huangapple go评论79阅读模式
英文:

How to get specific values in an array and output an average?

问题

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];
                
                double sum = 0.0;
                int count = 0;
                
                for (int i = 1; i < tokens.length; i++) {
                    sum += Double.parseDouble(tokens[i]);
                    count++;
                }
                
                double average = sum / count;
                
                System.out.println("Name: " + name + ", Average: " + average);
            }
            
            myScanner.close();
        }
        
        catch (Exception e) {
            System.out.println("Error reading file: " + myFile.getAbsolutePath());
        }
    }
}
英文:

I'm having trouble trying to figure out what exactly needs to be done in this scenario for the code to work properly. I need to output a text file containing a name and the average of a list of values on each line, the text files contains these things:

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

How do I output the average for each line in this scenario?
The code below is an example of a more simpler one with each line only containing one value, I just don't know how to modify the array list or the code to get the values I want.

    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(&quot;C:\\Users\\Byoma\\Downloads\\Assignment1.txt&quot;);
    		
    		try {
    			
    			Scanner myScanner = new Scanner(myFile);
    			
    			while (myScanner.hasNextLine()) {
    				String line = myScanner.nextLine();
    				
    				String[] tokens = line.split(&quot;,&quot;);
    				String name = tokens[0];
    				String average = tokens [1];
    				System.out.println(&quot;Name: &quot; + name + &quot;, Average: &quot; + average);
    			}
    			
    			myScanner.close();
    		}
    		
    		catch (Exception e) {
    			System.out.println(&quot;Error reading file: &quot; + myFile.getAbsolutePath());
    		}
    	}
    }

答案1

得分: 1

假设你列出的每个示例中的人名都位于文本文件中的单独一行,将以下代码插入到你现有的代码中,并做出少量修改,就能解决这个问题。

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; // 初始化一个 double 变量来求和
                for (int i = 1; i < tokens.length; i++) {
                    sum += Double.parseDouble(tokens[i]); // 将文本文档中的值解析为 double
                }
                double average = sum / (tokens.length - 1); // 通过将总和除以值的数量来计算平均值
                System.out.println("姓名:" + name + ",平均值:" + average);
            }

            myScanner.close();
        }

        catch (Exception e) {
            System.out.println("读取文件出错:" + myFile.getAbsolutePath());
        }
    }
}

注意:以上是你要求的代码的翻译部分,没有包括其他内容。

英文:

Assuming that each of the people that you listed for an example is on a separate line in the text file, adding a for loop to your current code and changing a few lines will solve this for you.

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(&quot;C:\\Users\\Byoma\\Downloads\\Assignment1.txt&quot;);

        try {

            Scanner myScanner = new Scanner(myFile);

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

                String[] tokens = line.split(&quot;,&quot;);
                String name = tokens[0];
                double sum = 0; //Initialized a double to sum the values
                for (int i = 1; i &lt; 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(&quot;Name: &quot; + name + &quot;, Average: &quot; + average);
            }

            myScanner.close();
        }

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

答案2

得分: 0

你从数组的第一个元素开始迭代,累加它们,然后将所有元素的总和除以元素的数量(请注意,我在累加总和时使用了int,但如果输入不是整数值,你可以使用floats或doubles,而且你不严格需要count变量):

public class MyClass {
    public static void main(String args[]) {
        String[] array = {"Name", "11", "5", "107"};
        int accumulated = 0; // 这将保存所有数字的总和
        int count = 0; // 我们用这个来跟踪有多少个数字
        for (int i = 1; i < array.length; i++) {
            // 添加数字,我们将它们转换为int,因为它们是字符串
            accumulated = accumulated + Integer.parseInt(array[i]); 
            count++;
        }  
        System.out.println("总和: "+accumulated);
        System.out.println("元素数量: "+count);
        float average = accumulated/count;
        System.out.println("平均值: "+average);
    }
}

输出:

总和: 123
元素数量: 3
平均值: 41.0
英文:

You iterate through the elements of the array starting with element 1 and accumulate them, then divide the total sum of the elements by the number of elements (note that I used int for the accumulated sum, but you can use floats or doubles if your input is not integer values, and that you don't strictly need the count variable):

public class MyClass {
    public static void main(String args[]) {
        String[] array = {&quot;Name&quot;, &quot;11&quot;, &quot;5&quot;, &quot;107&quot;};
        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 &lt; 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(&quot;Total sum: &quot;+accumulated);
        System.out.println(&quot;Number of elements: &quot;+count);
        float average = accumulated/count;
        System.out.println(&quot;Average: &quot;+average);
    }
}

Output:

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

huangapple
  • 本文由 发表于 2020年8月24日 06:05:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63552451.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定