Average of an array showing 1 - java

I have a program where the user inputs marks into the array and then gets the average value
This is using Jcreator
My problem is that when I ask for the average on my program,it says that the average is 1
This is my code :
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int averageEnglish = english.length / 10;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish
English is an int array
int[] english = new int [10];
averageEnglish is a variable
int averageEnglish;

10/10 equals 1. pretty normal.
what you need to do is get the sum of all elements, and divide them by the length of the array.
also: the IDE you use is not really relevant

english.length/10 is not the average value of the array, its simply the length (10) of the array divided by 10, which is 1. You need to sum up all values of the array and divide the sum by the length of the array.
Often you want to present the result not only as an integer but with a few decimals, store the sum and average result in a double.
double sum = 0;
for (int i = 0; i < english.length; i++) {
sum += english[i];
}
double average = sum / english.length;

You are dividing the array's length by the constant 10 (which just happens to be the length), so naturally you'd get 1. You should sum all values of the array and only then divide them by its length:
double englighSum = 0;
for (int i = 0; i < english.length; ++i)
englishSum += english[i];
}
double englishAverage = englishSum / english.length;

If you want user to fill the array, you need to use Scanner object.
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of grades: ");
int n = scanner.nextInt();
double[] english = new double[n];
for(int i=0; i<n; i++)
{
System.out.println("Please enter the grade for grade " + (i+1) + ":");
english[i] = scanner.nextDouble();
}
scanner.close();
Than you may use Markus Johnsson's code to proceed.

You anticipated the size of the array and assumed it is always 10 which is the first mistake, then you did your division based on the number of array elements not their sum:
int[] english = new int[10];
/* Now we assume you did some stuff here to fill the array. */
//averageEnglish
public void averageEnglish()
{
System.out.println("The Average Mark Of English Is");
int noOfElements = english.length; // The divisor
int sum = 0; // The dividend
for (int i = 0; i < noOfElements; i++)
{
sum += english[i];
}
// Here is your Average (Should be of type double since there will be floating points)
double averageEnglish = sum / noOfElements;
System.out.println("-----------");
System.out.println(averageEnglish);
System.out.println("-----------");
}//End of averageEnglish

The value of english.lenght is always 10. As in this example:
int[] english = new int [10];
It doesn't matter what data the english array holds, its lenght is always 10.
In order to do the proper calculation use the data, not the lenght of the array.

Related

How to find out variance from array of numbers?

New to Java here! I have to have the user enter 10 numbers and store them in an array (of doubles). After that I need to calculate:
Mean: I have that done and I need it to get the variance & std dev requires knowing the variance.
Variance: aka the average of the squares of the distance from the mean. The part I'm confused with. For each number in the array, I have to subtract the number from the mean, square the result, and then add the square to a running total. After that I have to divide the running total by the number of values (10).
Lastly, Standard deviation: aka the square root of the variance
I have to print all the results rounded to 2 decimal places.
Example: if my dataset was just {4, 7.5, 8}, then the mean is (4 + 7.5 + 8)/3 = 19.5/3 = 6.5.
Variance = ((6.5 - 4)^2 + (6.5 - 7.5)^2 + (6.5 - 8)^2
)/3 = (6.25 + 1 + 2.25)/3 = 9.5/3 = 3.17
Standard Deviation = √3.17 = 1.78
What I need help with is the math to find out the variance. I am not sure how to take a running total or how to square root numbers in parenthesis.
public class Statistics {
public static void main(String[] args) {
int userNumbers;
Scanner scan = new Scanner(System.in); // Creating Scanner object
System.out.print("Enter the 10 numbers: ");
userNumbers = scan.nextInt();
double array[] = new double[userNumbers];
double mean;
double variance;
for (int i = 0; i < array.length; i++) {
userNumbers += userNumbers;
mean = userNumbers / 10;
}
for (int i = 0; i < array.length; i++) {
variance = mean - userNumbers;
}
System.out.print("The variance is:" + );
System.out.print("The standard deviation is: " + Math.sqrt(variance));
}
}
In this code
for (int i = 0; i < array.length; i++) {
variance = mean - userNumbers;
}
you are overwriting the value of variance in each iteration of the loop, so only the last value would be kept.
Also, for both loops, you want to use the elements in the array
Try adding to the value
for (int i = 0; i < array.length; i++) {
variance += mean - array[i];
}

How to calculate the percentage of numbers that are greater than average.?

public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg)
{
percentage=(arr[i]*100/6);
}
}
System.out.println("Percentage is: "+percentage+"%");
}
For example, if 3 of the elements of the array are greater than average, percentage is 3*100/6=50%
Your calculations are wrong at the bottom part.
for(int i=0;i<arr.length;i++){
if(arr[i]>avg)
{
percentage=(arr[i]*100/6);
}
}
here, the correct calculation would be
for(int i=0;i<arr.length;i++){
if(arr[i]>avg)
{
percentage += (100/6);
}
}
you have to add the count the number of times arr[i] is greater than average and multiply the count with 100/6. The above code does exactly that.
NB: The percentage variable should be a floating point number not an integer
First, to compute the global average, do it at the end, using the array length tobe more generic
double sum=0;
for(int i=0; i<6; i++){
arr[i] = input.nextInt();
sum += arr[i];
}
avg = sum/input.length;
System.out.println("Average is: "+avg);
Then to compute the part that are the greater than the average, find how many values are greater then divide by the total number :
double greaterAvg = 0;
for(int i=0;i<arr.length;i++){
if(arr[i]>avg){
greaterAvg++;
}
}
double percentage = 100 * greaterAvg / input.length
System.out.println("Percentage is: "+percentage+"%");
I used double type to remove int division problem : Int division: Why is the result of 1/3 == 0?
To calculate the percentage of elements having a value greater than
average. first, you have to find the count of those elements and then divide it
with the total number of elements
Try this:
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
int count = 0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg)
{
count=count+1;
}
}
System.out.println(count);
percentage = (count*100)/6;
System.out.println("Percentage is: "+percentage+"%");
}
Output:
Enter all the elements:
1 2 3 4 5 6
Average is: 3
3
Percentage is: 50%
You need to find the total number of values that are greater than the average. Then you take that total number and divide it by the max, then multiple by 100 to return the percentage. For example, if we use 6, 5, 4, 3, 2, 1; The average is 3. The total number greater than 3 is 3 (6, 5, 4). We then take 3 (total) and divide it by max (6) to get .5 then multiply by 100 to get 50 (50%).
array = 6, 5, 4, 3, 2, 1
average = 3
max = 6
percentage = average / max * 100
public static void main(String[] args) {
int avg=0,sum=0,percentage=0;
Scanner input = new Scanner(System.in);
int[]arr=new int [6];
System.out.println("Enter all the elements: ");
for(int i=0; i<6; i++)
{
arr[i]=input.nextInt();
sum+=arr[i];
avg=sum/6;
}
System.out.println("Average is: "+avg);
int greaterThan = 0;
for(int i=0;i<arr.length;i++)
{
if(arr[i]>avg) {
greaterThan++;
}
}
percentage = (int) (((double) greaterThan / (double) arr.length) * 100D);
System.out.println("Percentage is: "+percentage+"%");
}
You can use a counter variable initialized to zero to count the elements first, then you can simply count the percentage using COUNTER * 100 / (number of elements)
You're calculating the avg in the loop, that's not efficient as the value get crushed at each iteration. It's better to keep only the sum in the loop and calculated the avg after the first loop.
This being said, there are only two main (functional) issues in your code:
The first one is the percentage processing in the loop - you're missing the "+=" and should not use arr[i] value.
The second one is the accuracy of the percentage, should be double (e.g) instead of int (same for the average - if really needed).
To sum up :
Declare percentage as double : double percentage = 0;
Replace percentage=(arr[i]*100/6); => percentage += (100.0/6);
[Optional] Truncate/round the percentage for display: e.g. System.out.printf("Percentage is: (%.2f) %%", percentage);
Cheers!

How to print out an altered dynamic array

I think I have swapped the first and last numbers of a dynamic array with each other and am at a total loss as to how to print the array with the numbers swapped.
Ideally, with the program working, the user is supposed to enter in the number of numbers they want to enter and then they will type each number in individually. Then it is supposed to output (along with standard deviation, the mean, and the original array order) the array in order, except the first number entered and the last number entered are switched. How would you go about printing the new array with the switched numbers?
Here is my code so far:
import java.util.Scanner;
import java.lang.Math;
public class Project_1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("How many numbers would you like to enter? ");
int N = scan.nextInt();
float sd, mean;
float Sum = 0;
float Square = 0;
float [] numbs = new float[N];
System.out.println("Enter your numbers below: ");
for (int i = 0; i < N; i++){
numbs[i] = scan.nextFloat();
Sum += numbs[i];
}
mean = Sum/N;
scan.close();
for (int j = 0; j < N; j++){
Square = (numbs[j] - mean) * (numbs[j] - mean);
}
sd = (float)Math.sqrt(Square/N);
System.out.println("The mean is: " + mean);
System.out.println("The standard deviation is: " + sd);
for (int k = 0; k < N; k++){
if (k == N-1){
System.out.print(numbs[k]);
}else{
System.out.print(numbs[k] + ", ");
}
}
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
}
}
You can swap the integers by doing the following,
int temp = numbs[N-1];
numbs[N-1] = numbs[0];
numbs[0] = temp;
Hope this helps :)
I did not realize that I would just have to enter another simple if statement to print it out. I was confused as to where the edited array was saving to, not realizing that it was just saving to the original array. Thank you all for the help.
In the end this is what I used for the code (in regards to my program specifically):
float lastNumb = numbs[numbs.length-1];
numbs[numbs.length-1] = numbs[0];
numbs[0] = lastNumb;
for (int g = 0; g < N; g++){
if (g == N-1){
System.out.print(numbs[g]);
}else{
System.out.print(numbs[g] + ", ");
}
Heres the output:
How many numbers would you like to enter? 5
Enter your numbers below:
1
2
3
4
5
The mean is: 3.0
The standard deviation is: 0.8944272
1.0, 2.0, 3.0, 4.0, 5.0
5.0, 2.0, 3.0, 4.0, 1.0

Sum and Averages of an Array

I am working on an array problem for my college course and I'm trying to find the sum and the average of an array. Here's the code I have so far.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
//declare the array values
weeks[0]= 2;
weeks[1]= 4;
weeks[2]= 8;
weeks[3]= 10;
weeks[4]= 14;
weeks[5]= 16;
weeks[6]= 20;
weeks[7]= 22;
weeks[8]= 24;
weeks[9]= 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
I know that the average works but I'm stuck on the sum. The problem I'm having is I cant seem to initialize the values in the array so that I can provide a sum for them. What am I doing wrong or what am I missing?
You have two problems in your code;
A) For-loop assignment
You don't need to make the first assignment, just adding sum to the week[index] is ok;
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
B) Calculating the average
Sum is defined as an int which is a primitive integer, because of that, the division of an integer to an integer, the output is an integer which is not precise. Output of the division (45/10) is casted to integer, then assigned to double which is rounded off to 4, then casted to double again, and '4.0' became the result.
To avoid this unprecise result, cast sum to the double as below;
average = (double)sum / weeks.length;
The corrected version of your code is as below;
Demo
public class Module55 {
public static void main(String args[]) {
// declare the array to have 10 items for 10 weeks
// also declare sum as an int and average as a double to accommodate for
// decimal points
int[] weeks = new int[10];
int sum = 0;
double average = 0;
// declare the array values
weeks[0] = 2;
weeks[1] = 4;
weeks[2] = 8;
weeks[3] = 10;
weeks[4] = 14;
weeks[5] = 16;
weeks[6] = 20;
weeks[7] = 22;
weeks[8] = 24;
weeks[9] = 26;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Output
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
And a note for scope
And one last note about the scope, check out this code;
for (int index = 0; index < weeks.length; index++)
weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
In the for-loop, because that no brackets are used, only the first statement under the for-loop will be considered in the scope of the loop by the compiler. That's why, for the next line, the compiler is giving error about the index because index is defined inside the scope of the for-loop.
you need to use brackets in your for loop. currently your code is evaluating like this:
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index;
}
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
you want your code to evaluate like this
for (int index = 0; index < weeks.length; index++)
{
weeks[index] = index; //logical issue, what does this line achieve?
sum = sum + weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
This will at least solve your procedural problems but you will still need to take a look at your logic. Try using breakpoints to debug your code.
A very simple way to achieve this in Java 8 is to use the built in mechanisms for gathering statistics:
int[] weeks = {3, 4, 6, 9, 10};
IntSummaryStatistics stats = IntStream.of(weeks).summaryStatistics();
System.out.println("sum = " + stats.getSum() + "; average = " + stats.getAverage());
for (int i = 0;i < weeks.length) {
sum += weeks[i];
}
System.out.println("Sum is:" + sum);
First of all, you simply don't need the line weeks[index] = index;.
And for average you have to cast the sum to double if you want to get the average in double as you have declared the sum as int.
public class Module55
{
public static void main(String args[])
{
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = {2,4,8,10,14,16,20,22,24,26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++)
//weeks[index] = index;
sum = sum + weeks[index];
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0)
average = (double)sum / weeks.length;
else
average = 0;
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
The total miles ran in 10 weeks is 146
The average of the miles ran in 10 weeks is 14.6
Summing an array of numbers and dividing by n to get the average like this will not get the correct value - you should not compute the average using integer division.
Also, this approach might work for the example shown, but not in general. For example, try using this code to find the average of these two value: (INT_MAX-6) and (INT_MAX-2).
The corrected code. While calculating average you have cast on of the varibale to double else you will get the average as integer
public class Mod55 {
public static void main(String args[]) {
//declare the array to have 10 items for 10 weeks
//also declare sum as an int and average as a double to accommodate for decimal points
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = 0;
double average = 0;
// determine sum of the array values
for (int index = 0; index < weeks.length; index++) {
sum += weeks[index];
}
System.out.println("The total miles ran in 10 weeks is " + sum);
// determine the average of the array values
if (weeks.length != 0) {
average = (double)sum / weeks.length;
} else {
average = 0;
}
System.out.println("The average of the miles ran in 10 weeks is " + average);
}
}
Java8 You could achieve the same thing like this.
int[] weeks = new int[]{2, 4, 8, 10, 14, 16, 20, 22, 24, 26};
int sum = Arrays.stream(weeks)
.sum();
double average = Arrays.stream(weeks).average().orElse(0);
you can find this handy with lambdas.The code looks something like this.
int weeks[] = {1,2,3,4};
List<Integer> asd = IntStream.of(weeks).boxed().collect(Collectors.toList());
//asd.forEach(System.out::println);
//this outputs average
System.out.println(asd.stream().mapToDouble(val -> val).sum()/asd.size());
//this outputs sum
System.out.println(asd.stream().mapToInt(val -> val).sum());
//another way to achieve this thanks to commenter
System.out.println(IntStream.of(asd).summaryStatistics());

Java - Finding even numbers and the percent of them within an array

This is the question that I need to figure out:
Write a method called percentEven that accepts an array of integers as a parameter and returns the percentage of even numbers in the array as a real number. For example, if the array stores the elements [6, 2, 9, 11, 3] then your method should return 40.0. If the array contains no even elements or no elements at all, return 0.0.
Here is what I have so far:
import java.util.*;
public class Change {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Let's find the range.");
System.out.println("Enter five numbers to find the range.");
int num = console.nextInt();
int[] list = new int[num];
System.out.println("The numbers you entered are: " + list.length);
System.out.println();
percentEven(list);
}
public static void percentEven(int[] num){
int percent = 0;
int even = 0;
for(int i = 0; i < num.length; i++){
if(num[i] % 2 == 0){
even++;
}
}
percent = (even / num.length) *100;
System.out.println("The percent of even numbers is: " + percent);
}
}
When I run it, I get 100 as the percent.
Two issues here:
Cast one of them to a double or float.
percent = (even / (double) num.length) *100;
The other issue is that you never assign the numbers any value, so they are all 0. 0 % 2 is equal to 0, so the list is, by definition, 100% even.
You should also have a base case in the method when nums == {}, which would return 0.0 as the assignment states.
There are three major problems in your code:
You are reading only ONE integer, not five
You use this single integer to define the LENGTH of the array, not the content (so you don't put the integer into the array. So the array contains only zeroes, which means that all of them are even.
You are doing wrong integer arithmetic (as Obicere already stated in his answer). But this doesn't have any effect, as all elements of the array are even, so the result will be 100 in any case.
You are almost there. But you are initializing and storing the array wrong way. Do this
int num = console.nextInt();
int[] list = new int[num];
System.out.println("Enter " + num + " numbers");
for(int i = 0; i < num; i++) {
list[i] = console.nextInt();
}
System.out.println("The numbers you entered are: " + java.util.Arrays.toString(list));
System.out.println();
and also do as other suggested.
Write
percent = even * 100 / num.length;
Changing the order of the operations will make the integer division business work in your favour - you'll get a value rounded down to the next lowest percentage, rather than rounded down to zero.
Also fix the problem with all the numbers being zero by reading them from the keyboard, as in tintinmj's answer.
import java.util.*;
public class percentEvenClass
{
public static void main(String[] args){
int[] list = {6, 2, 9, 11, 3};
int percentEven_Result = percentEven(list);
System.out.println(percentEven_Result);
}
public static int percentEven(int[] list){
int count = 0;
int percent = 0;
for (int i=0; i<list.length; i++){
if (list[i] % 2 == 0){
count++;
}
percent = (count * 100)/ list.length;
}
return percent;
}
}

Categories