java - 如何使用两个类将两个整数相乘,第一类包含方法 int calculateMultiplication (int, int),第二类包含主要方法?
问题描述
我需要这个程序的帮助。我需要将用户输入的两个整数相乘,然后使用int calculateMultiplication (int, int)方法计算结果。第一个类包含变量和方法的声明,第二个类包含所有打印的主方法。我不知道如何调用 calculateMultiplication 方法在我的最终打印中实现,它给出“第一个用户输入(我得到)和第二个用户输入(我得到)的乘法是结果(我没有)。
public class JavaApplication19 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.print("Enter the first int number: ");
int num1 = input.nextInt();
Two Num1 = new Two();
Num1.setN1 (num1);
int numOne = Num1.getN1();
System.out.print("Enter the second int number: ");
int num2 = input.nextInt();
Two Num2 = new Two();
Num2.setN2 (num2);
int numTwo = Num2.getN2();
}
}
This is the part I need help on: (this is just what i have so far)
System.out.println("The multiplication of " + numOne + " and " + numTwo + " is" + product + "." );
Two Result = new Two();
int result = Result.calculateMultiplication(num1, num2);
class Two {
private int result;
private int n1;
private int n2;
public int getN1(){
return n1;
}
public void setN1(int _n1){
n1 = _n1;
}
public int getN2(){
return n2;
}
public void setN2(int _n2){
n2 = _n2;
}
public int calculateMultiplication(int n1, int n2){
int answer = this.n1 * this.n2;
return result;
}
}
解决方案
注意实例变量和方法参数。
这两个类的写法可能有点不同:
public class Two {
private int n1;
private int n2;
private int result;
public void setN1(int n1) {
this.n1 = n1;
}
public void setN2(int n2) {
this.n2 = n2;
}
public void multiply() {
this.result = this.n1 * this.n2;
}
public int getResult() {
return this.result;
}
}
它有两个私有int
实例变量,n1
和n2
.
int num1 = 10; // for example
int num2 = 20; // for example
Two two = new Two();
two.setN1(num1);
two.setN2(num2);
two.multiply();
int result = two.getResult();
从这里你可以对这些值做任何你需要的事情。