所以我们必须创建一个执行以下操作的Rational类。在Java中创建一个包含Rational类的项目。该类表示Rational数字。它应该只有2个字段num和denom。它应该具有以下公共方法(以及所需的任何其他私有方法):
我有在Intellij IDEA中完成的代码,但它不会让我运行该程序。我知道我在大多数情况下都会遇到错误,但我相信这只是因为我没有把东西放在正确的位置或者留下一些东西。这是我到目前为止所做的。
import java.util.Scanner;
public class Rational {
private int num;
private int den; //fields
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("")
public Rational( int n, int d){
num = n;
den = d;
if (d == 0) {
num = 0;
den = 1;
System.out.println("Denominator is 0. Enter a number other than 0 next time.");
}//close if
int g = gcd(num, den);
num = n / g;
den = d / g;
}//close Rational
public String toString() {
if (den == 1) {
return num + "";
} else {
return num + "/" + den;
}
}//close toString
private Rational add(Rational r) {
int newNum = (this.num * r.den) + (r.num * this.den);
int newDen = r.den * this.den;
return new Rational(newNum, newDen);
}//close add
private static int gcd(int m, int n) {
if (0 == n) {
return m;
} else {
return gcd(n, m % n);
}//close else
}//close gcd
}//close main
}//close class
答案 0 :(得分:0)
public Rational(int n, int d){ // put Your Constructor Out of the main First
num = n;
den = d;
if (d == 0) {
num = 0;
den = 1;
System.out.println("Denominator is 0. Enter a number other than 0 next time.");
}//close if
int g = gcd(num, den);
num = n / g;
den = d / g;
}//close Rational
}
public String toString() { //put methods Outside of Main
if (den == 1) {
return num + "";
} else {
return num + "/" + den;
}
}//close toString
private Rational add(Rational r) { //put methods Outside of Main
int newNum = (this.num * r.den) + (r.num * this.den);
int newDen = r.den * this.den;
return new Rational(newNum, newDen);
}//close add
private static int gcd(int m, int n) { //put methods Outside of Main
if (0 == n)
return m;
else
return gcd(n, m % n);
}//close gcd
public static void main (String [] args) { //here is your Main Method.
System.out.println("");
// call Your Methods Accordingly.
} // main Closed
} //class Closed
main
方法。它应该在主框之外。main
方法中。再次编译错误。main
(如果实例方法)或直接使用类名称(如果静态方法)从object
内部调用这些方法。