所以我是一名學習Java的學生。我目前正在忙於一項任務,但我一直陷入一些if-else邏輯。修復了我自己的If-Else語句
我的任務要求我寫一個有理數(如72/14)的類文件,顯示它,將其分解成最低的形式(在這種情況下是36/7),將有理數作爲價值,最後顯示最大的共同因素。我遇到的問題是,我的代碼沒有篩選出這樣一個事實:例如,72/13是理性數字可以變得最小的事實,但是我知道它不會崩潰,而是反過來我把它換成了72/14的值搜索,並且這樣不能正常工作。
我的代碼:
public class QTwoAssiThree
{
private int numerator;
private int denominator;
public void writeOutput()
{
if (getGCD(numerator, denominator) >= 2)
{
System.out.println(toString() + " is the simplified rational number.");
System.out.println(getValue() + " is the value of the two rational numbers as one number.");
System.out.println((getGCD(numerator, denominator) * 2) + " is the largest common factor.");
}
else if (getGCD(numerator, denominator) == 1)
{
System.out.println(getValue() + " is the value of the two rational numbers as one number.");
System.exit(0);
}
}
public QTwoAssiThree()
{
numerator = 0;
denominator = 0;
}
public QTwoAssiThree(int initialNum, int initialDenom)
{
if (denominator % 2 == 0)
{
numerator = initialNum;
if (initialDenom > 0)
{
denominator = initialDenom;
System.out.println(toString() + " is the rational number entered.");
simplify(numerator, denominator);
}
else
{
System.out.println("Invalid value added as the denominator! Only positive integers should be used.");
System.exit(0);
}
}
else if (denominator % 2 == 1)
{
System.out.println(toString() + " is what was entered, and is already in its simplest form.");
}
}
private void simplify(int newNum, int newDenom)
{
numerator = newNum/getGCD(newNum, newDenom);
denominator = newDenom/getGCD(newNum, newDenom);
}
private static int getGCD(int x, int y)
{
int difference = x % y;
return difference;
}
private double getValue()
{
double doubleValue = (double)numerator/(double)denominator;
return doubleValue;
}
public String toString()
{
String fraction = Integer.toString(numerator) + "/" + Integer.toString(denominator);
return fraction;
}
}
現在,請忽略的事實是,我依然對知識的Java程序員規模偏低。我很感激任何關於此的指針,因爲我陷入困境,無法真正弄清楚如何設置它。有兩個地方我使用if-else
來查看它是否有效,第一個地址是: public void writeOutput()
和public QTwoAssiThree(int initialNum, int initialDenom)
構造函數。最初沒有任何if-else
陳述,但代碼確實工作,但不適用於不均勻的整數。
public class QTwoAssiThreeDemo
{
public static void main(String[] args)
{
QTwoAssiThree rationalNumbers = new QTwoAssiThree(72, 14);
rationalNumbers.writeOutput();
}
}
是用來演示整個班級。
我的產出應該是基本上什麼樣的情況如下:
72/14 is the rational number entered.
36/7 is the simplified rational number.
5.142857143 is the value of the two rational numbers as one number.
2 is the largest common factor.
和
72/13 is what was entered, and is already in its simplest form.
5.538461538 is the value of the two rational numbers as one number.
的代碼進行優化,在長相醜陋,我知道,但任何幫助,將不勝感激,我會在我提交作業之前,先做好一切工作,讓它看起來更漂亮些。
首先,......你實現*錯* GCD算法('getGCD'):如果你給什麼'14'和'72',而不是'72'和'14 '?另一個反例是'4'和'2' –
我認爲'getGCD()'有問題,你能說出它該做什麼嗎? – theRoot
你的問題在'getGCD()'中,以及你正在'writeOutput()'中以最簡單的理性形式 – Prashant