我是编程的初学者。我认为问题出现在writeOutput中,因为当我尝试从readInput中添加.getsum时,它可以工作。 这是我的代码
import java.util.Scanner;
public class Calculator {
int userInput;
public void readInput(){
Scanner sc = new Scanner(System.in);
Addition add = new Addition();
Subtraction sub = new Subtraction();
Multiplication prod = new Multiplication();
Division quo = new Division();
System.out.print("Pick what method you want to apply\n [1]Addition\n [2]Subtraction\n [3]Multiplication\n [4]Division\n: ");
userInput = sc.nextInt();
System.out.print("Enter number1: ");
int num1 = sc.nextInt();
add.setNumber1(num1);
sub.setNumber1(num1);
prod.setNumber1(num1);
quo.setNumber1(num1);
System.out.print("Enter number2: ");
int num2 = sc.nextInt();
add.setNumber2(num2);
sub.setNumber2(num2);
prod.setNumber2(num2);
quo.setNumber2(num2);
}
public void writeOutput(){
Addition add = new Addition();
Subtraction sub = new Subtraction();
Multiplication prod = new Multiplication();
Division quo = new Division();
我无法上班。它总是等于零。
if(userInput == 1){
System.out.println("The Sum is " + add.getSum());
}
else if(userInput == 2){
System.out.println("The Difference is " + sub.getDifference());
}
else if(userInput == 3){
System.out.println("The Product is " + prod.getProduct());
}
else if(userInput == 4){
System.out.println("The Quotient is " + quo.getQuotient());
}
else{
}
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.readInput();
calc.writeOutput();
}
}
答案 0 :(得分:2)
在进行输出时,您正在创建新对象。创建每个Addition的实例,sub ...然后在输出中使用该对象或使其成为静态对象。
答案 1 :(得分:0)
不是制作计算类的本地对象,而是制作这些实例变量,然后在两种方法中使用相同的变量,请尝试下面的代码段:
import java.util.Scanner;
public class Calculator {
int userInput;
Addition add = new Addition();
Subtraction sub = new Subtraction();
Multiplication prod = new Multiplication();
Division quo = new Division();
public void readInput(){
Scanner sc = new Scanner(System.in);
System.out.print("Pick what method you want to apply\n [1]Addition\n [2]Subtraction\n [3]Multiplication\n [4]Division\n: ");
userInput = sc.nextInt();
System.out.print("Enter number1: ");
int num1 = sc.nextInt();
add.setNumber1(num1);
sub.setNumber1(num1);
prod.setNumber1(num1);
quo.setNumber1(num1);
System.out.print("Enter number2: ");
int num2 = sc.nextInt();
add.setNumber2(num2);
sub.setNumber2(num2);
prod.setNumber2(num2);
quo.setNumber2(num2);
}
public void writeOutput(){
if(userInput == 1){
System.out.println("The Sum is " + add.getSum());
}
else if(userInput == 2){
System.out.println("The Difference is " + sub.getDifference());
}
else if(userInput == 3){
System.out.println("The Product is " + prod.getProduct());
}
else if(userInput == 4){
System.out.println("The Quotient is " + quo.getQuotient());
}
else{
}
}
public static void main(String[] args) {
Calculator calc = new Calculator();
calc.readInput();
calc.writeOutput();
}
}