0

I'm trying to make a calculator in which you have to first say what kind of operator you want to use, and then add 2 numbers to calculate it. To do this, I use 2 classes 1 for the inputs and calculations and the other one for the operators. In the second class is the error for this answer = int1 - int2;. The error I get is that I can't use the operators on com.company.Main. Can anyone tell me how to fix the error?

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    mathe decrease = new mathe();
    int int1, int2;
    mathe answer = new mathe();
    mathe operator= new mathe ();

    System.out.println( "What do you want to do?");
    String chosenOperator = input.nextLine();

    System.out.print("Add a number: ");
    int1 = input.nextInt();

    System.out.print("Add another number: ");
    int2 = input.nextInt();

    if (chosenOperator.equals("Decrease") || chosenOperator.equals("-"))
         operator.decrease(answer.toString());

    else if (chosenOperator.equals("Adding") || chosenOperator.equals("+"))
        operator.adaption(answer.toString());

    else if (chosenOperator.equals("Times") || chosenOperator.equals("*"))
        operator.times(answer.toString());

}

public class mathe {
    

    Main int1 = new Main();
    Main int2 = new Main();

    public void decrease(String answer){
        answer = int1 - int2;
        System.out.println(answer);

    }
    public void adaption(String answer){
        answer = int1 + int2;
        System.out.println(answer);

    }
    public void times(String answer){
        answer = int1 * int2;
        System.out.println(answer);
    }


}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Darney
  • 11
  • 1
  • 1
    Does this answer your question? [Why doesn't Java offer operator overloading?](https://stackoverflow.com/questions/77718/why-doesnt-java-offer-operator-overloading) – Nowhere Man Aug 30 '20 at 00:57

1 Answers1

2

The reason is because int1 and int2 aren't actually int values, instead they are object references to the class Main. What you would do, if you're trying to access two ints from the main class you could do something like this:

public class Main 
{
    int a; 
    int b; 

    public Main(int a, int b) 
    { 
        this.a = a; 
        this.b = b; 
    }

    //create getters and setters to initialize and get the values 
}

Then in the seperate class, you can call them like this:

Main m = new Main(1, 2);
public void decrease(String answer){
    answer = m.getIntOneValue() - m.getIntTwoValue();
    System.out.println(answer);

}

Now you can access the values across any class you want, as long as you correctly access their values. Refer to this link for more examples:

beastlyCoder
  • 2,349
  • 4
  • 25
  • 52