Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (7k points)

I have a program that asks the user to choose several elements. The program then asks the user to choose the numbers as many times indicated by the number of elements. How do I find the variance of this set of numbers using only arrays and either while or for loops?.

This is my code:

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 Answer

0 votes
by (13.1k points)

You can do it like this:
 

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);

    }

}

Related questions

0 votes
1 answer
asked Mar 30, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Mar 11, 2021 in Java by Jake (7k points)
0 votes
1 answer
asked Mar 7, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Mar 6, 2021 in Java by dante07 (13.1k points)

Browse Categories

...