I have so far a program that asks the user to choose a number of elements. The program then asks the user to choose numbers as many times indicated by the number of elements. How would I find the variance of this set of numbers using only arrays and either while or for loops. Nothing too fancy as I am in high school. Below is my current code:
//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);
}
}
Your program may be like:
//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();
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.