2015-05-07 204 views
-1

我是java新手,需要幫助。我的while循環不起作用。它不會執行除count之外的其他任何操作。while循環沒有執行

對於這個問題,我需要做的是具有突變和附件的方法分數類。然後,我必須使分子和分母最低形式,所以我使用while循環通過使用模塊來查找最大公約數。任何其他評論家也表示感謝。

public class Fraction { 
    private int numerator; 
    private int denominator; 
    public Fraction(){ 

    } 
    public Fraction(int num, int den){ 
     this.numerator = num; 
     this.denominator = den; 
    } 

    public void setNumerator(int numerator){ 
     this.numerator = numerator; 
    } 
    public void setDenominator(int denominator){ 
     this.denominator = denominator; 
    } 
    public double divided(){ 
     double divide = (double)this.numerator/this.denominator; 
     return divide; 
    } 
    public String printFraction(){ 
     int numerator = greatestCommmonNumetaror(); 
     return ""; 
    } 
    private int greatestCommmonNumetaror(){ 
     int count = 1; 
     int first; 
     int mod; 
     while(count != this.numerator){// need help with this 
      mod = this.numerator%count; 
      if(mod != 0){ 
       first = count; 
       if(first < count){ 
        first = count; 
       } 
      } 
      count++; 
     } 
     return 1; 
    } 
} 
+1

你說的意思是「它不執行除算什麼。」 – Shahzeb

+0

放入一些'println's,這樣你就知道運行的是什麼。 –

+2

我不確定你的while循環試圖實現什麼。你設置了一堆變量,但似乎並沒有使用它們,最後你只返回「1」。你能用文字來描述該算法試圖做什麼嗎? –

回答

1

擺脫this.numerator while循環,如果你調用一個很好的執行。 剛剛加入夫婦的System.out.println的,你可以看到它正在運行:

private int greatestCommmonNumetaror(){ 
    int count = 1; 
    int first; 
    int mod; 
    System.out.println("Outside while: count is "+count+" and this.numerator is "+this.numerator); 
    while(count != this.numerator){// need help with this 
     System.out.println("In while: Count is "+count); 
     mod = this.numerator%count; 
     System.out.println("In while: mod is "+mod); 
     if(mod != 0){ 
      first = count; 
      System.out.println("In while and if: first is "+first+" and count is "+count); 
      if(first < count){ 
       first = count; 
       System.out.println("In while and if and if: first is "+first+" and count is "+count); 
      } 
     } 
     count++; 
    } 
    return 1; 
} 

public String printFraction(){ 
    int numerator = greatestCommmonNumetaror(); 
    return ""; 
} 

而且下面提到的代碼添加到調用printFraction:

public static void main(String[] args){ 
    Fraction fraction = new Fraction(3,5); 
    fraction.printFraction(); 
} 

而且你可以看到輸出:

Outside while: count is 1 and this.numerator is 3 
In while: Count is 1 
In while: mod is 0 
In while: Count is 2 
In while: mod is 1 
In while and if: first is 2 and count is 2 

所以它進入while循環。

*編輯:雖然使用System.out.println你應該能夠看到這個問題與你的算法,但仍,如果您有任何進一步的問題,能否請您解釋一下與你的例子算法。

-2

只需使用分子得到循環

+0

爲什麼要投票呢? –

+1

我不是dvter,但你的答案完全沒有解決他的問題。 – Aify

+0

我想並沒有什麼區別 –