-3

can anyone help me with this java work; i am having difficulties

Write a program to add together the following marks and find the average: 45, 56, 34, 89 Output all the marks, the total (sum) and the average mark.

so far I have done this.

public class Average {
    public static void main (String args []) {
        int Average;
        Average = (45 + 56 + 34 + 89) / 4;

        System.out.printin(45 + 56 + 34 + 89) / 4;
    }
}

can anybody help me finish this off please ?

16
  • Are you expected to use an array or just a bunch of hard-coded numbers?
    – PakkuDon
    Feb 10, 2014 at 12:58
  • What are you not able to do? Try, you can do this.
    – Rahul
    Feb 10, 2014 at 12:59
  • 1
    Please use a meaningful title. Feb 10, 2014 at 12:59
  • No array just hard coded numbers thanks
    – Savvvooo
    Feb 10, 2014 at 13:00
  • 1
    Thank you people i done it !! thanks alot for everyones help i understand what i done wrong :)
    – Savvvooo
    Feb 10, 2014 at 13:42

1 Answer 1

2

It will be something like rhis:

public class Average {
    // Can contain any number of `int` numbers
    static int[] numbers = {45, 56, 34, 88};

    public static void main(String[] args) {
        // Create an instance of `Average` class to call non `static` method 

        final double result = new Average().calculateAverage(numbers);
        System.out.println("result = " + result);

    }

    double calculateAverage(int[] array) {
        int count = 0; // count of numbers
        int sum = 0;   // count of sum all of numbers 
        for (int currentNumber : array) {
            count++;
            sum += currentNumber;
        }
        // You need to divide by double value to not lost decimal part,
        // so cast `count` to `double`.
        return sum / (double) count;
    }
}

The result is:

result = 55.75
9
  • 7
    Yea great ... now he doesn't need to learn anything to complete his homework. (Not least because the chances of him understanding your code right now seem pretty small.)
    – Stephen C
    Feb 10, 2014 at 13:09
  • You know, he can learn by example maybe. I will add comments for better understanding :/ Feb 10, 2014 at 13:11
  • 1
    And that would reduce the chances of him understanding even more! Hint: look at the level of understanding of Java exhibited by his attempt.
    – Stephen C
    Feb 10, 2014 at 13:12
  • 2
    @Shubham - That's unfair. Maybe he simply has only been taught simple expressions and data types ... so far.
    – Stephen C
    Feb 10, 2014 at 13:15
  • 1
    thank; you very much but I want to be able to understand what I done wrong this is correct I think but Its completely different to what I started thank you for taking you time to help me just wanted a little help not the whole answer but thanks you very much
    – Savvvooo
    Feb 10, 2014 at 13:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.