i have to create an array and a method call for the average. but for some reason it is not average all numbers, its only returning the last number. I have asked my instructor for help and she said the math is correct it should work. But no other help from her. What have I done wrong?
public static void main(String[] args) {
double[] myArray = new double[2];
initialize(myArray);
double avg = getAverage(myArray);
System.out.println(avg);
output(avg);
}
public static void initialize(double[] myArray) {
//myArray = new double[1000];
for(int i = 0; i < myArray.length; i++) {
myArray[i] = (int) ((Math.random()*500)*1);
System.out.println(myArray[i]);
}
}
/**
*
* #param myArray
* #return
*/
public static double getAverage(double[] myArray) {
int sum = 0;
for (int i = 0; i < myArray.length; i++) {
sum += myArray[i];
}
return sum / myArray.length;
}
public static void output(double avg) {
System.out.println("The average is " + avg);
}
The key is in this line:
sum / myArray.length
...since both sum and myArray.length are integers, Java performs integer division, not floating point division, which essentially means it drops the decimal component of the result.
Casting one of the values to a double first will force a floating point division to occur.
You're also storing the sum as an int, which could again introduce a source of error since the array contains doubles. In this case you're ok because you're casting everything you put into the array to an int first, which begs the question as to why you're using a double array in the first place?
As an aside, this is a bit odd:
((Math.random()*500)*1);
There's no need to multiply the result by 1 here - that won't do anything.
What is the problem here? The answers are coming correctly. Please check again. The interesting fact is that the third number is always same as the average of all three. But the average computation is correct. That may be how Math.random() generates random numbers internally. The third is the average of the other two. Try out four or five numbers instead of three numbers and check your answers.
Related
This question already has answers here:
How do you find the sum of all the numbers in an array in Java?
(28 answers)
Closed 1 year ago.
This is my code using loops. Assume that num is not null or empty;
public int[] num;
public double[] sumNum() {
double[] sum;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
If you want to devise a function to sum the values of an array, consider the below:
public int sumNum(int[] num) {
int sum = 0;
for (int i = 0; i < num.length; i++) {
sum = sum + num[i];
}
return sum;
}
It doesn't make sense to return a double for a function like this, but you still can. I changed it to int since num is always int as per its declaration. I'm only making an assumption to what you really wanted.
Also consider taking num as argument for the function, thereby giving it local scope within the function. You could keep it global but again, I'm making an assumption of what you really want. Plus, it allows for re-using this function if you ever wanted to find the sum of something else.
You also want some initial value for sum: since you're summing the values in an array, I initialized sum to 0. Otherwise, when you do sum = sum + num[i], what exactly is sum initially? You need some starting point.
ne of my projects assigned was to create an array for 10 variables which the user inputs and to have the program output the average of the input number as well as listing the numbers below the average. I am able to obtain the average without an issue but my code to return the numbers below the average seems to not be doing the job. For example if I input into the array the values [1,2,3,4,5,6,7,8,9,10] the average outputs as 5.5 (which is good) but the output I want from BelowAverage is 1,2,3,4,5 can anyone help me?
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
return aveless;
}
No need to use wrappers, you could use double instead of Double.
Your variable naming is weird, why do you have an ArrayList of averages instead of numbers?
Follow Java naming conventions:
firstWordLowerCaseVariable
firstWordLowerCaseMethod()
FirstWordUpperCaseClass
ALL_WORDS_UPPER_CASE_CONSTANT
and use them consistently
You already have a method that calculates the average, why not use it?
So, for example, your code might look like this (with slight modifications):
public static int belowAverage(List<Double> numbers) {
double avg = calculateAverages(numbers); //Go, get the average using the method you already have
int aveless = 0;
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) < avg) { //Instead of comparing the numbers array size, compare the number against the average.
aveless++;
}
}
return aveless;
}
I added opening and closing curly braces for the for loop as I think it's easier to read that way.
I also changed the return type to int instead of double on this method as you only want to count, so, decimal point is not needed and moved the System.out.println() call inside the calculateAverage() method to the main method.
I also changed the parameter type to the interface one (from ArrayList to List)
Your problem seems to bee on this line:
if(Averages.size() < avg) aveless++;
You should be checking Averages.get(i) < avg instead, otherwise what is the point of looping?
If I understand correctly, and you want a list with all the numbers below the average, you should change the return value and the code, like this:
public static ArrayList<Double> BelowAverage(ArrayList<Double> Averages) {
// You already have a method for calculating the average, so use it
double avg = CalculateAverages(Averages);
ArrayList<Double> aveless = new ArrayList<Double>();
int i;
for(i = 0; i < Averages.size(); i++){
double number = Averages.get(i);
if(number < avg){
aveless.add(number);
}
}
return aveless;
}
There are several problems with your code. Let's go through them one at a time.
First problem:
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i); //this line
avg /= Averages.size();
You are simply reassigning the value of avg in the loop. What you want to do is to keep adding values to it. Replace = with += to get avg += Averages.get(i);.
Second problem:
for(i = 0; i < Averages.size(); i++)
if(Averages.size() < avg)
aveless++;
Here you are checking whether avg is larger than the size of the list which is not what you want to be doing. What you wonder is whether avg is larger than the values in the list. You need to replace Averages.size() with Averages.get(i). This is a relatively easy mistake to spot because the loop is not really achieving anything right now, so look out for things like this.
Edit: There are a few other problems as well. avg should be a double and not an int, because ints cannot store decimal places and there is no guarantee that your average is a whole number, so you will get a rounding error. Furthermore, your method should return an int instead of a double because "the number of values below average" is always an integer.
To count the number of 'numbers' which have less value than the average, you should compare each element inside that array with the average, not with the size of the array. Try it as follows:
public static double BelowAverage(ArrayList<Double> Averages) {
int i, aveless = 0; double avg = 0;
for(i = 0; i < Averages.size(); i++)
avg = Averages.get(i);
avg /= Averages.size();
for(Double a : Averages)
if(a < avg) aveless++;
return aveless;
}
I'm trying to write a script to calculate the average GPA of the class and which shows the lowest and highest grades achieved by the students.
I'm trying how to get the average of the 12 numbers. I know I need to add all the number and divide them 12. Can someone give me a few tips on how I can do this. Thansk!!
If you are using Java 8 there are good facilities for stats:
IntSummaryStatistics stats = Arrays.stream(grades).summaryStatistics();
Then you can use stats.getMin, stats.getAverage etc.
If, on the other hand, this is a homework assignment then you probably should write your own code to do this rather than use the Java library.
Suppose the 12 students have the grades in the array intArr
public int calculateAverage(){
int[] intArr = {1,2,3,4,5,6,7,8,9,10,11,12};
//Total number of students grades in the array
int totalStudents = intArr.length;
//Variable to keep the sum
int sum = 0;
for (int i = 0; i < totalStudents; i++){
sum = sum + intArr[i];//Add all the grades together
}
int average = sum/totalStudents;
return average;
}
What #SiKing said, what code have you tried? Show us what you've coded!
#nitinkc's code is on the right track although not completely correct by OO standards.
Here's what I have. This is just a function. You must implement your runner yourself assuming you have just a main runner class...
// initialise and pass in your array into your function
public static double calculateAverage(int[] array) {
// double because averages are more than likely to have decimals
double gradesTotal = 0;
// loop through each item in your array to get the sum
for(int i = 0; i < array.length; i++) {
gradesTotal = gradesTotal + array[i];
}
// return the sum divided by number of grades
return gradesTotal/array.length;
}
i am beginner and here is the method I am struggling with.
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...
public static double percentEven(int[]a){
int count = 0;
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent =(count/a.length)*100.0;
}
return percent;
}
i keep returning 0.0 when array contains a mix of even and odd elements but works fine for all even element array or all odd array? i can't see where the problem is?
thanks in advance.
count/a.length returns 0 since you are dividing two ints, and the second operand is larger than the first. Change it to (double)count/a.length in order to perform floating point division.
Alternately, change the order of operations to :
percent = 100.0*count/a.length;
For a simple division like 2*100.0/5 = 40.0, the above logic would work fine but think about the situation where we have 51*100.0/83 the output would be less readable and its always advisable to truncate the percentage to a limited decimal digits.
An example:
int count = 51;
Double percent = 0.0;
int length = 83;
percent = count*100.0/length;
System.out.println(percent);
output: 61.44578313253012
When you truncate it:
Double truncatedDouble = new BigDecimal(percent ).setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(truncatedDouble);
output: 61.446
#Bathsheba : Well said, thanks for the suggestion.
Here is sample code :
public class PercentEven {
public static void main(String args[]){
int count = 0;
int[] a={2, 5, 9, 11, 0}; // this can be dynamic.I tried diff values
double percent = 0.0;
if (a.length > 0){
for ( int i = 0; i < a.length; i++){
if ( a[i] % 2 == 0){
count++;
}
}
percent = (100*count/a.length);
}
System.out.println(percent);
}
}
List<Integer> numbers = Arrays.asList(a);
int number = numbers.stream().filter(n->n%2==0).count();
int percent = number*100.0/numbers.size();
I have done this in java 8
I have an array that takes student grades from an input. I have to make a method that will find the average of the numbers within the array. Here is the code i have so far...
int mark = Integer.parseInt(input.getText());
if(mark <= 100){
marks.add(Integer.parseInt(input.getText()));
input.setText("");
warningLbl.setText("");
}
else{
warningLbl.setText("Please enter an number between 0-100");
}
I want to take the contents in the array 'marks' and get an average for them then append it in my text area
public static double getAverage(int[] marks)
{
int sum = 0;
for(int i : marks) sum += i;
return ((double) sum)/marks.length;
}
This is the method i have to find the average, but i dont know how to use this method and get it to print in a text area
If you want to find the average stored in an array , try the following function.
public static double average(int[] marks)
{
int sum = 0;
double average;
for(int element: marks)
{
sum = sum + element;
}
average = (double)sum / marks.length;
return average;
}
Hope it helps ! :)
The above method is used to find average in an array(primitive type) , but to find average in List type array(wrapper class) , we have to iterate through each element in the list by this way and do the required calculations :
public static String average(Integer[] marks)
{
int sum = 0;
double average;
for (int i = 0; i < marks.size(); i++)
{
sum = sum + marks.get(i);
}
average = (double) sum / marks.size();
String averageString = Double.toString(average);
return averageString;
}
This returns your average in string type directly.
There are several problems with your current code.
Using input.getText(); twice will mean it's going to prompt for input twice. Have a single line like int mark = Integer.parseInt(input.getText()); then use the mark variable wherever it's needed.
In order to test if the number is between 0 and 100 (I'm assuming this needs to be inclusive), that if statement would need to be (mark >= 0 && mark <= 100).
I assume you want to get multiple students' grades/marks, so it may be a good idea to enclose your code in a for or while loop, depending on how you want it to operate. However, since this will be of variable length I'd recommend using a List over an array for resizing.
Finding the average is easy. Just use a foreach loop to sum up all the numbers, then divide that by the array length.