我正在尝试使用多个类制作一个简单的计算器。我可以一对一上课,但是现在我想尝试使用两堂课。我在从OperationClass调用某些变量(fnum,snum,答案)时遇到麻烦。
如果我现在运行程序,则返回0。
我尝试将OperationClass中的变量fnum,snum和answer公开,但这没有用。
我也尝试了公共类OperationClass扩展Calculator。那也不起作用。
我知道我缺少一些非常简单的东西。我只是无法指出。

计算器类:

import java.util.Scanner;

public class Calculator{

    public static void main(String[] args) {

        OperationClass operationObject = new OperationClass();


        Scanner input = new Scanner(System.in);
        double userInput;
        int userChoice;

        System.out.print("Please Enter The First Number: ");
        userInput = input.nextDouble();
        System.out.print("Please Enter The Second Number: ");
        userInput = input.nextDouble();
        System.out.println("Please Select Operation to Perform:");
        System.out.println("1-Addition");
        System.out.println("2-Subtraction");
        System.out.println("3-Division");
        System.out.println("4-Multiplication");
        userChoice = input.nextInt();

        switch (userChoice){
        case 1:
            operationObject.addition();
            System.out.println();
            break;
        case 2:
            operationObject.subtraction();
            break;
        case 3:
            operationObject.division();
            break;
        case 4:
            operationObject.multiplication();
            break;
        }


    }

}


OperationClass:

public class OperationClass{

    double fnum, snum, answer;

    public void addition(){
        answer = fnum + snum;
        System.out.println(answer);
    }

    public void subtraction(){
        answer = fnum - snum;
        System.out.println(answer);
    }

    public void division(){
        answer = fnum / snum;
        System.out.println(answer);
    }

    public void multiplication(){
        answer = fnum * snum;
        System.out.println(answer);
    }
}

最佳答案

您需要将用户输入的值传递给OperationClass类。
有多种方法可以做到这一点。

1)选项一。更改方法以接受一些参数,例如:

public double addition(double fnum, double snum ){
      return fnum+snum;
}


并在Calculator中获取结果,您可以执行以下操作:

 case 1:
    System.out.println(operationObject.addition(userInput1, userInput2));
    break;


您必须将用户输入存储在2个不同的变量中。

2)将用户输入的内容存储在OperationClass中作为类变量。

public class OperationClass{
     .....
     public void setFNum(double fnum){
         this.fnum = fnum
     }
     public void setSNum(double snum){
         this.snum = snum
     }
     ......
}


并传递Calculator中的值,您可以执行此操作。

public static void main(String[] args) {

    ....

    OperationClass operationObject = new OperationClass();
    Scanner input = new Scanner(System.in);
    double userInput;
    userInput = input.nextDouble();
    operationObject.setFNum(userInput);
    userInput = input.nextDouble();
    operationObject.setSNum(userInput);

    ....
}

07-24 21:06