数组的平均值并与名称关联

时间:2014-12-08 19:45:40

标签: java arrays average

有谁知道如何在这个简单的程序中显示参与者的平均比赛时间? 随时间显示关联的跑步者名称也很棒。 我认为我有正确的数组结构,并已接受用户输入。 感谢您提供的任何帮助。这是我的代码......

import java.util.Scanner;
 public class RunningProg
 {
    public static void main (String[] args)
    {
    int num;

    Scanner input= new Scanner (System.in);

    System.out.println("Welcome to Running Statistical Analysis Application");
    System.out.println("******************************************************************* \n");

    System.out.println("Please input number of participants (2 to 10)");

    num=input.nextInt();

    // If the user enters an invalid number... display error message... 
    while(num<2|| num >10)
    {
    System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");

        num=input.nextInt();
    }

    // declare arrays
    double resultArray [] = new double [num]; // create result array with new operator
    String nameArray [] = new String [num];// create name array with new operator
    // Using the num int will ensure that the array holds the number of elements inputed by user

      // loop to take in user input for both arrays (name and result)
    for (int i = 0 ; i < nameArray.length ; i++)
        {
            System.out.println ("Please enter a race participant Name for runner " + (i+1) );
            nameArray[i] = input.next();

            System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
            resultArray[i] = input.nextDouble();
        }

1 个答案:

答案 0 :(得分:0)

这似乎是一个家庭作业问题,所以这里是你如何解决你的问题,在伪代码中

参与者的总平均比赛时间是通过将所有结果相加并除以结果的数量来计算的:

sum = 0
for i = 0 to results.length      // sum up all the results in a loop
    sum = sum + results[i]          
average = sum / results.length   // divide the sum by the amount of results to get the average

当您阅读用户输入并存储跑步者的姓名和结果时,执行总结会更好。原因是它会更有效率(不需要第二个循环来执行总和)并且代码会更清晰(会有更少的代码)。

通过迭代包含名称和结果的两个数组并在相应的索引处打印值,可以显示具有他们次数的跑步者:

for i = 0 to results.length
    print "Runner: " + names[i] + " Time: " + results[i]

这是有效的,因为您有相同数量的结果和名称(results.length == names.length),否则您最终会遇到ArrayIndexOutOfBounds例外。


另一种方法是使用Java的面向对象特性并创建一个名为Runner的对象:

class Runner {
    String name;
    double result;
    Runner(String n, double r) {
        result = r;
        name = n;
    }
}

然后使用数组来存储这些跑步者:

Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
    System.out.println ("Please enter a race participant Name for runner " + (i+1) );
    String name = input.next();
    System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
    double result = input.nextDouble();
    runners[i] = new Runner(name, result);
}

然后你可以迭代一下runner数组并打印名称和结果......这是伪代码:

for i = 0 to runners.length
    print runners[i].name + " " + runners[i].result