Ask Me Help Desk

Ask Me Help Desk (https://www.askmehelpdesk.com/forum.php)
-   Java (https://www.askmehelpdesk.com/forumdisplay.php?f=440)
-   -   Method to calculate average in java not working properly (https://www.askmehelpdesk.com/showthread.php?t=818656)

  • Nov 23, 2015, 11:58 AM
    lost java
    Method to calculate average in java not working properly
    I am trying to call in a method to calculate average from data that has been input in an array using the scanner class, but somehow the average formula is not working properly. I have tried correcting it for a long time but the output looks something like "[I@34d0cdd0" in place of numbers. Can you please help point out what am I doing wrong? I am new to this, any help is really appreciated. Thanks.
    import java.util.Scanner;
    public class Programxx {
    public static void main(String[] args) {
    //Declare variables
    int number;


    Scanner input = new Scanner (System.in);

    System.out.println("Enter the numbers you want to calculate the average of : ");
    //get total numbers needed for average
    number = input.nextInt();

    //validate input (for average there should at least be 2 numbers)
    while (number <=1)
    {
    System.out.print("You didn't enter a valid value. Enter the numbers you want to calculate the average of : ");
    number = input.nextInt();
    }

    //create array for numbers entered
    int[] ar = new int[number];

    for (int I = 0; I < number; I++) {
    System.out.print("Number " + I + " : ");
    ar[i] = input.nextInt();
    }
    input.close(); // input close

    average (ar);
    System.out.println("The total average for the array of numbers is : " + ar);
    }
    // method to calculate and return the average of passed array
    public static double average (int [] array) {

    double avgs;
    double total=0;

    for (int I = 0; I < array.length; I++)
    {
    total =array[i] + total;
    }
    avgs = (total/array.length);
    return avgs;
    }
    }
  • Nov 24, 2015, 09:04 AM
    CravenMorhead
    When you call average(ar) you're discarding the return value and using the address for the array to print out.

    Try adding a new variable and capture the return value from the average method. Then output that variable instead of ar.

    Does that make sense?

  • All times are GMT -7. The time now is 08:39 PM.