using a meathod to find the average value of an array [duplicate] - java

This question already has answers here:
How to calculate mean, median, mode and range from a set of numbers
(7 answers)
Closed 2 years ago.
I'm writing a program that displays the Maximum, Minimum, and average of an array
So far I have methods for the max and min but not for the average.
My code:
class Test
{
public static void main(String[] args)
{
int[] arr = {5,12,-3,7,3,22,31,2,16,56};
System.out.println(minValue(arr));
System.out.println(maxValue(arr));
System.out.println(avgValue(arr));
}// end of Main
// Array Methods
public static int minValue(int[] nums)
{
int minValue = nums[0];
for(int i=1;i < nums.length; i++){
if( nums[i] < minValue){
minValue = nums[i];
}
}
return minValue;
}
public static int maxValue(int[] nums)
{
int maxValue =nums[0];
for(int i=1;i < nums.length ;i++){
if( nums[i] > maxValue){
maxValue = nums[i];
}
}
return maxValue;
}
public static int avgValue(int[] nums)
{
int temp = 4;
return temp;
}
}// end fo class
Right now the method to find the average is filled with a placeholder integer that always returns "4"
How would I write a message to find the average of my array?

This is the proper way:
public static float avgValue(int[] nums)
{
float sum = 0.0f;
float avg = 0.0f;
for(int i=0; i < nums.length;i++){
sum += nums[i];
}
avg = sum/nums.length;
return avg;
}

An easy way would be:
public static double avgValue(int[] nums) {
int total = 0;
for(int i = 0; i < nums.length; i++) {
total = total + arr[i];
}
double average = total / (double) nums.length;
return average;
}

Using Java Streams
int[] data = {1,5,4,9,2,1,4,7,8};
IntSummaryStatistics s = Arrays.stream(data).summaryStatistics();
System.out.println("Average: " + s.getAverage());
System.out.println("Count: " + s.getCount());
System.out.println("Min: " + s.getMin());
System.out.println("Max: " + s.getMax());
System.out.println("Sum: " + s.getSum());
Output
Average: 4.555555555555555
Count: 9
Min: 1
Max: 9
Sum: 41

Related

Finding largest gap between consecutive numbers in array Java

I'm currently working on a homework assignment and the final task of the assignment is to write a method to find the largest gap between consecutive numbers in an unsorted array. Example: if the array had the values {1,2,3,4,5,20} the gap would be 15. Currently the array is holding 20 values generated at random.
I'm totally lost for how I would make this happen. Initially my idea for how to solve this would be using a for loop which runs through each value of the array with another loop inside to check if the current value is equal to the previous value plus 1. If it is then store that number as the minimum in the range. Another problem I ran into was that I have no idea how to store a second number without overwriting both numbers in the range. Basically nothing i've tried is working and could really use some help or at least a nudge in the right direction.
What the method does right now is only store the value for "a" after it finds a number that isn't consecutive in the array.
Here's the code I have so far
import java.util.Arrays;
class Main {
public static void main(String[] args) {
Main m = new Main();
m.runCode();
}
public void runCode()
{
Calculator calc = new Calculator();
calc.makeList(20);
System.out.println("List:");
calc.showList();
System.out.println("Max is: " + calc.max());
System.out.println("Min is: " + calc.min());
System.out.println("Sum is: " + calc.sum());
System.out.println("Ave is: " + calc.average());
System.out.println("There are " + calc.fiftyLess() + " values in the list that are less than 50");
System.out.println("Even numbers: " + calc.Even());
}
}
class Calculator {
int list[] = new int[20];
public void makeList(int listSize)
{
for (int count = 0; count < list.length; count++) {
list[count] = (int) (Math.random() * 100);
}
}
public void showList()
{
for (int count = 0; count < list.length; count++)
{
System.out.print(list[count] + " ");
}
}
public int max()
{
int max = list[0];
for (int count=0; count<list.length; count++){
if (list[count] > max) {
max = list[count];
}
}
return max;
}
public int min()
{
int min = list[0];
for (int count=0; count<list.length; count++){
if (list[count] < min) {
min = list[count];
}
}
return min;
}
public int sum()
{
int sum = 0;
for (int count=0; count<list.length; count++){
sum = sum + list[count];
}
return sum;
}
public double average()
{
int sum = sum();
double average = sum / list.length;
return average;
}
public int fiftyLess()
{
int lessThan = 0;
for (int count =0; count<list.length;count++)
{
if (list[count] < 50)
{
lessThan++;
}
}
return lessThan;
}
public int Even()
{
int isEven = 0;
for (int count = 0; count<list.length;count++)
{
if (list[count] % 2 == 0)
{
isEven++;
}
}
return isEven;
}
public int Gap()
{
int a = 0;
int b = 0;
int gap = math.abs(a - b);
for (int count = 1; count<list.length;count++)
{
if (list[count] != list[count] + 1)
{
a =list[count];
}
}
}
}
By using the java8 stream library you could achieve this in fewer lines of code.
This code segment iterates the range of the array, and subtracts all consecutive numbers, and returns the max difference between them or -1, in case the array is empty.
import java.util.stream.IntStream;
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference =
IntStream.range(0, list.length - 1)
.map(i -> Math.abs(list[i + 1] - list[i]))
.max().orElse(-1);
System.out.println(max_difference);
}
}
Alternatively you could do this with a traditional for loop.
class Main {
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 5, 20};
int max_difference = -1;
int difference;
for (int i = 0; i < list.length - 1; i++) {
difference = Math.abs(list[i + 1] - list[i]);
if(difference > max_difference)
max_difference = difference;
}
System.out.println(max_difference);
}
}
Output for both code segments:
15

Array Index Out of Bounds Exception in 1 of 3 Methods [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
This should be a fairly simple homework assignment, but I've been pounding my face on it for a while now ... When executed, it should just populate an array and find the mean and standard deviation. I'm getting an out of bounds exception, but only in the arrayDeviation method. Any direction would be appreciated.
import java.util.Scanner;
import java.util.Random;
public class StandardDeviation
{
//declare global variables
final static int ELEMENTS = 100;
public static void main(String [] args)
{
//declare variables
final int RANGE = 500;
int[] numList = new int[ELEMENTS];
Random rand = new Random();
//populate array
for(int count = 0; count < ELEMENTS; count++)
{
numList[count] = rand.nextInt(RANGE) + 1;
}
//call printArray
printArray(numList);
//call arrayAverage
double mean = arrayAverage(numList);
System.out.println("\nMean: " + mean);
//call arrayDeviation
double standardDeviation = arrayDeviation(numList, mean);
System.out.print("Standard deviation: " + standardDeviation);
} //end main
//output 10 elements per line
public static void printArray(int[] list)
{
final int ELEMENTS_PER_LINE = 10;
for(int count = 0; count < ELEMENTS; count++)
{
System.out.printf("%-4d", list[count]);
if ((count + 1) % ELEMENTS_PER_LINE == 0)
{
System.out.println();
}
}
}
//returns average as double
public static double arrayAverage(int[] list)
{
int sum = 0, count;
double average;
for(count = 0; count < ELEMENTS; count++)
{
sum = sum + list[count];
}
average =(double) sum / count;
return average;
}
//calculate and return standard deviation
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++);
{
sum = sum + Math.pow((list[count] - mean), 2);
}
standardDeviation = Math.sqrt(sum / 2);
return standardDeviation;
}
} //end class
Staring at this code for like 10 minutes I couldn't see why it's giving that Exception.Pasting it in Netbeans and it instatly highlights an empty for-loop
public static double arrayDeviation(int[] list, double mean)
{
double sum = 0.0, standardDeviation;
int count;
for(count = 0; count < ELEMENTS; count++); //This semicolon is your
//problem
{
sum = sum + Math.pow((list[count] - mean), 2);
}

Why is my code coming out with the wrong output? Is my insert class wrong?

I have to create classes to be implemented with the main class someone else has and for some reason I am not getting the right outputs, I'm not sure is my calculations are off which I don't think they are or my insert class is wrong.
Expected Output:
Median = 44.5
Mean = 49.300
SD = 30.581
Actual Output:
Median = 0.0
Mean = 0.967
SD = 4.712
public class StatPackage {
int count;
double [] scores;
final int MAX = 500;
StatPackage() {
count = 0;
scores = new double[MAX];
}
public void insert (double value) {
if (count < MAX){
scores[count] = value;
++ count;
}
}
public double Mean () {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < scores.length; i++){
sum += (scores[i]);
count++;
}
double average = sum/count;
return average;
}
public double Median() {
int min;
int tmp;
int size;
for (int i = 0; i < scores.length - 1; i ++)
{
min = i;
for (int pos = i + 1; pos < scores.length; pos ++)
if (scores [pos] < scores [min])
min = pos;
tmp = (int)scores [min];
scores [min] = scores [i];
scores [i] = tmp;
}
double median = 0;
if (scores.length % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = (scores[((scores.length/2))]);
}
return median;
}
public double Variance () {
double variance = 0;
double sum = 0;
//For loop for getting the variance
for(int i = 0; i < scores.length; i++){
sum += scores[i];
variance += scores[i] * scores[i];
count++;
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return (varianceFinal);
}
public double StdDev (double variance) {
double sum = 0;
for(int i = 0; i < scores.length; i++){
sum += scores[i];
variance += scores[i] * scores[i];
count++;
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}
}
The length of your scores array is 500, so every time you are using it in a calculation you are running that 500 times. You need to make your loop continuation conditions dependent on the number of values in the array, no the actual length of the array. I would be careful of your variable naming as well, you are using count in two places sometimes and it has global scope! This method stores the number of values in the array in the count variable:
public void insert (double value) {
if (count < MAX){
scores[count] = value;
++count;
}
}
So use the count variable as the loop-continuation condition when you are getting values from the array, like so:
public double mean() {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
double average = sum / count;
return average;
}
That should help a little, I don't have time to check out your other methods but maybe this will give you a good starting place. I figured out what was happening by inserting print statements in your methods to make sure the values were as expected. It's a helpful thing to do when debugging. Your mean() method with the print statements looks like this:
public double mean() {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
// print statements for debugging
System.out.println("count is " + count);
System.out.println("sum is " + sum);
double average = sum / count;
return average;
}
Because the solution is easily found by debugging, I will only give you a hint:
The mean of 3, 4 and 5 is 4: (3+4+5)/3, not (3+4+5)/(n*3) where
n is a positive integer.
If you look at your mean and std and divide it by the expected result, you will see it's a rounded number.
Once you find the solution to 1 problem, you will immediately know why the other results are faulty as well =)

Finding the median and max value of an array in java

I used this code to calculate the max value and the median element in an array of integers, but when I call the methods in my client class, both of these two methods produce an output of zero. The name of the array is "grades" and it is made of randomly generated integers
import java.util.*;
public class StudentGrades {
private int [] grades;
//Constructor
public StudentGrades ( int students)
{
Random number = new Random();
grades = new int[students];
for (int i = 0 ; i < students ; i++)
{
grades[i] = number.nextInt(99) + 1;
}
}
double median;
public void median()
{
Arrays.sort(grades) ;
double median ;
if (grades.length % 2 == 0)
{
int indexA = (grades.length - 1 ) /2;
int indexB = (grades.length)/2;
median = ((double) (grades[indexA] + grades[indexB]))/2;
}
else
{
int medIndex = (grades.length-1) / 2;
median = grades[ medIndex ];
}
}
public double getMedian()
{
return median;
}
int max;
public int getHighest()
{
for(int i = 0 ; i < grades.length - 1 ; i++)
{
int max = 0;
if(grades[i] > max)
{
max = grades[i];
}
}
return max;
}
In my driver, I simply had to prove that the method worked correctly, so it's:
System.out.println(" The highest grade is" + grades.getHighest());
System.out.println("The median grade is" + grades.getMedian());
Few mistakes.
1.) Might be calling getMedian(), whereas the logic is inside median() method.
2.) Inside method, getHighest(),
a.) No need to loop the array, since array is already sorted. So i have commented the code.
Just get the value at last index of array.
public class Test {
static int max;
static double median;
static int[] grades = { 2, 3, 4, 5, 62, 34 };
public static void main(String args[]) {
Arrays.sort(grades);
median();
getHighest();
System.out.println(median);
System.out.println(max);
}
public static void median() {
if (grades.length % 2 == 0) {
int indexA = (grades.length - 1) / 2;
int indexB = (grades.length) / 2;
median = ((double) (grades[indexA] + grades[indexB])) / 2;
} else {
int medIndex = (grades.length - 1) / 2;
median = grades[medIndex];
}
}
public double getMedian() {
return median;
}
public static int getHighest() {
/* for (int i = 0 ; i < grades.length ; i++) {
if (grades[i] > max) {
max = grades[i];
}
}*/
max = grades[grades.length - 1];
return max;
}
Output
4.5
62

Return the amount of numbers below average

I am trying to write a program that returns the amount of numbers less than the average
For example, if I have the numbers 2, 3 and 4, the average would be (2.1+3.6+4.2)/3 = 3.3 and since 2.3 is below average it would return 1 as there is one number below the average.
I am getting an error that says
Type mismatch: cannot convert from double[] to int
My code:
public static void main(String[] args) {
double[] numbers = {2.1, 3.6, 4.2};
System.out.println(belowaverage(numbers));
}
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
for(int i = 0;i<ba.length;i++){
sum = sum + ba[i];
average = sum / ba.length;
if(ba[i]<average){
return ba;
}
}
You're trying to return the array ba which is the array holding your input data instead of the count.
You need to leave the computation of the average in your current for loop and then create a second for loop and an int count variable which you will increment each time you find a number in the ba array that is smaller than the average. Then outside of that loop you return count.
Also this line:
average = sum / ba.length;
Has to be outside of the first loop.
#Edit: others provided some code but it had either logical or compile time errors (not all of them I guess, the ones I checked) so here's a working version:
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
int count = 0;
for(int i = 0; i < ba.length; i++) {
sum = sum + ba[i];
}
average = sum / ba.length;
for(int i = 0; i < ba.length; i++){
if (ba[i] < average) {
count++;
}
}
return count;
}
You don't need to cast length to double as sum is of type double so the result will be promoted to the bigger type.
public static void main(String[] args) {
double[] numbers = {2.1, 3.6, 4.2};
System.out.println(belowaverage(numbers));
}
public static int belowaverage(double[] ba) {
double sum = 0;
int length = ba.length;
for (int i = 0; i < length; i++) {
sum += ba[i];
}
double average = sum / length;
int belowAvgCount = 0;
for (int i = 0; i < length; i++) {
if (ba[i] < average) {
belowAvgCount++;
}
}
return belowAvgCount;
}
This isn't going to work using only a single for loop, because you can't possibly compare anything to the average until you've calculated it.
Try separating your calculation of the average and the counting of terms below the average into two different loops:
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
for(double b : ba){
sum += b;
}
average = sum / ba.length;
int count = 0;
for(double b : ba){
if(b < average){
count++;
}
}
return count;
}
You need to work out the sum first, then compute the average and then count how many below this threshold.
try
public static int belowaverage(double[] ba) {
double sum = 0;
double average = 0;
int count = 0;
for(int i = 0;i<ba.length;i++){
sum = sum + ba[i];
}
average = sum / ba.length;
for(int i = 0;i<ba.length;i++){
if (ba[i] < average) count++;
}
return count;
}

Categories

Resources