-1

I have made this simple code which adds numbers together and finds the average. I get the error message shown in the title. The code below is; can someone please help me with the error when my tutor couldn't?

public class MathsQuiz {   

    public MathsQuiz(){
        int int1 = 45;
        int int2 = 56;
        int int3 = 34;
        int int4 = 89;
        int int5 = 4;
        int answer = 0;
     }

     public int add(int int1, int int2, int int3, int int4, int int5){
        int answer = ((int1 + int2 + int3 + int4)/int5);
        return answer;
     }

     public static final void main(String[] str){
        System.out.println ("MathsQuiz" + " " + answer);
        MathsQuiz mq = new MathsQuiz();
     }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Daniel G
  • 47
  • 8

1 Answers1

0

The problem is that you are referencing a variable that you have not declared on this line:

System.out.println ("MathsQuiz" + " " + answer);

I presume you want to reference the variable you declared in the add() method. The simplest way to go around this is to call the method directly instead of referencing the variable. Like this:

  public static final void main(String[] str){
        MathsQuiz mq = new MathsQuiz();
        System.out.println ("MathsQuiz: sum of 1,2,3,4,5" + ":" + mq.add(1,2,3,4,5);
   }
Verem Dugeri
  • 630
  • 9
  • 15
  • Do some research next time before posting a question here. – Verem Dugeri Oct 10 '16 at 21:56
  • 1
    ok i have done that and now it highlights this line and says "int answer = ((int1 + int2 + int3 + int4)/int5);" "java.lang.ArithmeticException: /by zero" and if i try to get rid of this line it messes up the rest of the code. p.s. i did do some research i looked through my java book and asked my tutor neither able to help so i came here – Daniel G Oct 10 '16 at 22:25