java中的数组加法?

时间:2013-10-11 20:01:54

标签: java arrays addition variance

到目前为止,我有一个程序要求用户选择一些元素。程序然后要求用户选择由元素数量指示的次数。如何仅使用数组以及while或for循环来查找这组数字的方差。没有什么比我在高中时更加花哨的了。以下是我目前的代码:

//write an app that finds the variance of a set of numbers
class temp1 {
    public static void main(String args[])
    {
    int counter = 0;
    String question;
    question = "How many elements do you want?: ";
    EasyReader console = new EasyReader();
    System.out.println(question);
    int answer;
    int answer2;
    answer = console.readInt();
    int[] numbers = new int[answer];
    int mean;
    System.out.println();
    while(true)
    {
    System.out.println("Please enter a number: ");
    answer2 = console.readInt();
    counter++;
    if(counter==answer)
    {
    break;
    }
    }
    mean = (numbers[0]+numbers[1]+numbers[2]+numbers[answer])/answer;
    System.out.print(mean);
    }
    }

1 个答案:

答案 0 :(得分:0)

您的计划可能如下:

//编写一个找到一组数字方差的应用程序

class temp1
{
    public static void main(String args[])
    {
        int counter = 0;
        String question;
        question = "How many elements do you want?: ";
        EasyReader console = new EasyReader();
        System.out.println(question);
        int answer;
        int answer2;
        answer = console.readInt();
        int[] numbers = new int[answer];
        int mean;
        System.out.println();
        while (true)
        {
            System.out.println("Please enter a number: ");
            answer2 = console.readInt();
            numbers[counter] = answer2;
            counter++;
            if (counter == answer)
            {
                break;
            }
        }
        counter = 0;
        int sum = 0;
        while(true)
        {
            sum = sum + numbers[counter];
            counter++;
            if(counter == answer)
            {
                break;
            }
        }
        mean = sum / answer;
        System.out.print(mean);
    }
}