简体   繁体   中英

Struggling to calculate average, min and max in java

I am currently struggling to calculate the average, minimum and maximum in my coding. I am receiving a lot of errors and not sure as to what I am doing wrong. Sorry if I am not providing enough information, I will update my post if needed. Also, I would appreciate if you can explain as to why you used that code so that I can understand please. Thank you.

EDIT - What I want it to do is when the user enters a set of numbers and finished inputting numbers, I want it to display the average of the numbers the user inputted after the histogram as well as the maximum and minimum. I assumed I would have to use my count variable as well as my num variable but still struggling in implementing it.

Errors I am receiving are shown in my coding below within the lines of coding.

import java.util.Scanner;

public class Histogram1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int[] array = new int[5000];
    int num = 0;
    int count = 0;
    int total = 1;
    int max = 0;
    int min = 0;

    System.out.println ("Enter students marks in the range 0 to 100\n");

    loop: for (count = 0; count <= total; count++)
    {
        System.out.println ("Enter a number:");
        num = scan.nextInt();
        if (num < 0 || num > 100)
        {
            break loop;
        }
        array[count] = num;
       total = count+1;
    }
    System.out.println ("How many times a number between 0-100 occur.");

    String[] asterisk = {"0- 29   | ", "30- 39  | ","40- 69  | ", "70- 100 | "}; //4 strings

    for (count = 1; count <= total; count++)
    {
        num=array[count];
        if (num >=0 && num <=29) asterisk [0] +="*";
        else if (num>29 && num <=39) asterisk[1] +="*";
        else if (num>39 && num <=69) asterisk[2] +="*";
        else if (num>69 && num <=100) asterisk[3] +="*";
    }
    for (count =0;count < 4;count++)
        System.out.println(asterisk[count]);
    System.out.println("The total amount of students is " + total);

    **int cannot be dereferenced** for (int i = 0; i < count.length; i++) {
    **array required, but int found** num += count[i];
    **array required, but int found** if (min > num[i]) {
    **array required, but int found** min = num[i];
        }
    **array required, but int found** if (max < num[i]) {
    **array required, but int found** max = num[i];
        }
    }
    **int cannot be dereferenced** double average = (double) num / count.length;
    System.out.printf(" min: " + min);
    System.out.printf("%n max: " + max);
    System.out.printf("%naverage: %.1f", average);
}
}
  • If you have an array, minimum is often calculated by first setting the initial minimum value to a known maximum value "infinity" or in this case 100. Next step would be to iterate over your set of values and check whether a value is below current minimum, and if so set minimum to that value.

     int min = 100; for (int i = 0; i < total; i++) { if (array[i] < min) { min = array[i]; } } 
  • for maximum, do the other way around, setting initial maximum value to 0 or negative "infinity" and check whether a value in the array is greater than current maximum value.

  • for average, sum all values and divide the result on the total amount of elements in the array.

     int sum = 0; for (int i = 0; i < total; i++) { sum += array[i]; } double avg = (double) (sum) / total; 

In java positive infinity as integer type is represented as Integer.MAX_VALUE and negative infinity: Integer.MIN_VALUE .

Let's assume we have an array of values: int[] values = { some values }

To calculate average:

  • loop through the array and calculate the sum
  • divide sum by number of elements

     int sum = 0; for(int i : values) { sum += i; } double average = (double)(sum) / values.length; 

To find min and max:

  • loop through the array and compare current element with min and max and set them appropriately

     int max = -2147483648; //set to min int value, -2^31 int min = 2147483647; //set to max int value, 2^31 - 1 for (int i : values) { if (i > max) max = i; if (i < min) min = i; } 

I see that the other posts have already answered how to calculate average, min, and max in an array, so I will only be tackling the error with your code.

You receive an error that says that int cannot be dereferenced :

tmp.java:48: int cannot be dereferenced
        for (int i = 0; i < count.length; i++) {
                                 ^

This stems from the fact that you have defined count as an int not as an array. In fact, all of the compiling errors come from here. The variable count will not have a length, nor can you access its elements (it has none). In the last part of your code (where the errors arise) you have confused count, min, and max as arrays, whereas they are actually just integers. Your code was close (had the proper idea), but I think you might have confused some of the syntax.

Because your array length is always 5000, I had to use the second for loop to calculate the minimum number. Otherwise, if I was to use the first for loop (that is now commented), the minimum number would always be 0 (if less than 5000 numbers inputted) because there would always be trailing elements that are = 0. I would suggest using an ArrayList instead, but my code for you uses the same array you created.

I commented everything I changed/added from your code:

public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);

    int[] array = new int[5000];
    int num = 0;
    int count = 0;
    int total = 0; // start this at 0, in case no inputs are valid
    double sum = 0; // make this a double to get a decimal average
    int max = 0; // start at the lowest possible number for max
    int min = 100; // start at the highest possible number for min
    double average = 0;

    System.out.println ("Enter students marks in the range 0 to 100\n");

    loop: for (count = 0; count <= total; count++)
    {
        System.out.println ("Enter a number:");
        num = scan.nextInt();
        if (num < 0 || num > 100 || total == 5000) // can't enter more than 5000 (array length restriction)
        {
            break loop;
        }
        array[count] = num;
        sum += num; // keep track of the sum during input
        total = count+1;
    }
    System.out.println ("How many times a number between 0-100 occur.");

    String[] asterisk = {"0- 29   | ", "30- 39  | ","40- 69  | ", "70- 100 | "}; //4 strings

    for (count = 1; count <= total; count++)
    {
        num=array[count];
        if (num >=0 && num <=29) asterisk [0] +="*";
        else if (num>29 && num <=39) asterisk[1] +="*";
        else if (num>39 && num <=69) asterisk[2] +="*";
        else if (num>69 && num <=100) asterisk[3] +="*";
    }
    for (count =0;count < 4;count++)
        System.out.println(asterisk[count]);
    System.out.println("The total amount of students is " + total);

    // calculate the average
    average = sum / total;

    // calculate the min and max
    // use this for loop if the length of the array is
    // the amount of the inputs from the user
    /*for (int i : array) // for every int in the array of inputted ints
    {
        if (i > max) max = i; // if this int in array is > the last recording max number, set the new max number to be this int
        if (i < min) min = i; // if this int in array is < the last recording min number, set the new min number to be this int
    }*/

    for (int i = 0; i < total; i++) // for every inputted int ( < total so that you exclude the trailing elements that are = 0)
    {
        if (array[i] > max) max = array[i]; // if this int in array is > the last recording max number, set the new max number to be this int
        if (array[i] < min) min = array[i]; // if this int in array is < the last recording min number, set the new min number to be this int
    }

    // my way of printing results
    //System.out.println("\n Average: " + average);
    //System.out.println("Max: " + max + "\n Min: " + min);

    System.out.printf(" min: " + min);
    System.out.printf("%n max: " + max);
    System.out.printf("%naverage: %.1f", average);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM