私は、ユーザーが2つの異なる分数を入力し、コンピューターが分数メソッドを実行してそれらが等しいかどうかをテストするプログラムに取り組んでいます。割り当ての追加の手順として、IllegalArgumentException をスローして分母の 1 つが 0 かどうかを識別し、プログラムを再起動します。Fraction クラスと testFraction クラスは次のとおりです。
分数クラス:
class Fraction {
private int numerator;
private int denominator;
Fraction() {
numerator = 0;
denominator = 1;
}
Fraction (int num, int den) {
numerator = num;
denominator = den;
if (denominator == 0){
throw new IllegalArgumentException (
"Denominator cannot be zero");
}
}
public void setNum(int num){
numerator = num;
}
public void setDen(int den){
denominator = den;
}
public int getNum(){
return numerator;
}
public int getDen(){
return denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
public boolean equals(Fraction other){
if (numerator * other.getDen() == denominator * other.getNum()){
return true;
}
else {
return false;
}
}
}
testFraction クラス:
import java.util.Scanner;
public class testFraction {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = 1;
int b = 1;
int c = 1;
int d = 1;
Fraction f1 = new Fraction(a, b);
Fraction f2 = new Fraction(c, d);
System.out.println("Enter the numerator of the first fraction: ");
f1.setNum(keyboard.nextInt());
System.out.println("Enter the denominator of the first fraction: ");
f1.setDen(keyboard.nextInt());
try{
int fraction = a/b;
}
catch (IllegalArgumentException e){
System.out.println(e.getMessage);
main(args);
}
System.out.println("\nEnter the numerator of the second fraction: ");
f2.setNum(keyboard.nextInt());
System.out.println("Enter the denominator of the second fraction: ");
f2.setDen(keyboard.nextInt());
System.out.println("\nFraction 1: " + f1);
System.out.println("Fraction 2: " + f2);
System.out.println("\nAre fractions equal? " + f1.equals(f2));
System.out.println(("\nWould you like to run the counter with a different integer? \n(1 for YES - 0 for NO): "));
int answer = keyboard.nextInt();
if (answer == 1){
System.out.println("\nLet's Rock 'n Roll! ");
main(args);
}
else if (answer == 0){
System.out.println("\nLater Dude! ");
System.exit(0);
}
}
}
try/catch で間違って作業しているように感じます。ご協力いただきありがとうございます。