简体   繁体   中英

How can you use operators on a variable from another class in java

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);
    }


}

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:

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