在 Main 中调用静态方法
Calling a Static Method In Main
如何在 main 中调用此 class 上的最后一个方法?我只是想 return 一个包含两个参数乘积的新 Rational 对象。每次我尝试在 main 中调用它时,我都不能在参数中使用整数,因为它只接受对象。那么,如果它只接受对象,我该如何将两个数字相乘。 (我不能将参数更改为整数,它是问题集的一部分)。您的帮助将不胜感激。这是我的代码:
public class Rational {
private int numer, denom;
public Rational(int numer, int denom){
this.numer = numer;
this.denom = denom;
}
public Rational(Rational rational){
rational = new Rational(numer, denom);
}
public void setNumber(int fum){
numer = fum;
}
public int getNumber(){
return numer;
}
public void setDenom(int Dum){
denom = Dum;
}
public int getDenom(){
return denom;
}
public Rational reciprocal(){
System.out.println(denom + "/" + numer);
return new Rational(denom, numer);
}
public static Rational multiply(Rational a, Rational b){
int bar = a.numer;
int bla = b.denom;
int multi = bar * bla;
System.out.println(multi);
return new Rational(bar,bla);
}
}
你可以这样称呼它:
public class Main {
public static void main(String[] args) {
Rational rational1 = new Rational(1,2);
Rational rational2 = new Rational(1,2);
Rational result = Rational.multiply(rational1, rational2);
}
}
如何在 main 中调用此 class 上的最后一个方法?我只是想 return 一个包含两个参数乘积的新 Rational 对象。每次我尝试在 main 中调用它时,我都不能在参数中使用整数,因为它只接受对象。那么,如果它只接受对象,我该如何将两个数字相乘。 (我不能将参数更改为整数,它是问题集的一部分)。您的帮助将不胜感激。这是我的代码:
public class Rational {
private int numer, denom;
public Rational(int numer, int denom){
this.numer = numer;
this.denom = denom;
}
public Rational(Rational rational){
rational = new Rational(numer, denom);
}
public void setNumber(int fum){
numer = fum;
}
public int getNumber(){
return numer;
}
public void setDenom(int Dum){
denom = Dum;
}
public int getDenom(){
return denom;
}
public Rational reciprocal(){
System.out.println(denom + "/" + numer);
return new Rational(denom, numer);
}
public static Rational multiply(Rational a, Rational b){
int bar = a.numer;
int bla = b.denom;
int multi = bar * bla;
System.out.println(multi);
return new Rational(bar,bla);
}
}
你可以这样称呼它:
public class Main {
public static void main(String[] args) {
Rational rational1 = new Rational(1,2);
Rational rational2 = new Rational(1,2);
Rational result = Rational.multiply(rational1, rational2);
}
}