2017-02-27 32 views
-4

這個程序是針對Java的。它意味着要做Collat​​z猜想。在我的明代碼應該工作,但是當我輸入7它打印出一堆22的我認爲它與java保存ints問題。java不能正確保存整數

import java.util.*; 
//If n is even, divide it by 2 to get n/2. If n is odd, multiply it by 3 . and add 1 
public class infNum { 
    private int num; 
    private int n; 
    private String comma = ", "; 

    public void start() { 
     System.out.println("enter a number"); 
     Scanner keyboard = new Scanner (System.in); 
     int n = keyboard.nextInt(); 
     num = n; 
    } 
    public void testEvenOdd() { 
     if((num % 2) == 0) { 
      ifEven(num); 
     } else { 
     ifOdd(num); 
     } 
    } 

    public void ifEven(int num) { 
     if(num == 1) { 
     return; 
     } else { 
     num = num/2; 
     System.out.print(num + comma); 
     testEvenOdd(); 
     } 
    } 

    public void ifOdd(int num) { 
     if(num == 1) { 
     return; 
     } else { 
     num = (num * 3) +1; 
     System.out.print(num + comma); 
     testEvenOdd(); 
     } 
    } 
} 
+1

好吧,'7'是一個奇數。 「7 * 3」是21,「21 + 1」是** 22。看起來你的程序完全符合你的要求。 –

+0

這是怎麼回事?起始方法在哪裏,如果是開始方法,其他方法都不會被調用? –

+0

這更多的是你的'testEvenOdd'方法檢查'num'實例變量的問題,而你的其他方法永遠不會更新它。目前他們只更新他們自己的參數,當方法結束時,參數超出範圍。 – azurefrog

回答

1

的代碼應該工作,但是當我進入7它打印出一堆 22的我認爲這是一個問題與Java節省整數。

問題似乎是你將實例變量與局部變量混合i.e你想要更新實例變量,而是更新了局部變量。這很容易解決,只需使用this關鍵字來區分它們。

例子:

import java.util.*; 
    //If n is even, divide it by 2 to get n/2. If n is odd, multiply it by 3 . and add 1 
    public class infNum { 
     private int num; 
     private int n; 
     private String comma = ", "; 

    public void start() { 
     System.out.println("enter a number"); 
     Scanner keyboard = new Scanner (System.in); 
     int n = keyboard.nextInt(); 
     this.num = n; 
    } 
    public void testEvenOdd() { 
     if((this.num % 2) == 0) { 
      ifEven(this.num); 
     } else { 
     ifOdd(this.num); 
     } 
    } 

    public void ifEven() { 
     if(this.num == 1) { 
     return; 
     } else { 
     this.num = this.num/2; 
     System.out.print(this.num + comma); 
     testEvenOdd(); 
     } 
    } 

    public void ifOdd() { 
     if(this.num == 1) { 
     return; 
     } else { 
     this.num = (this.num * 3) +1; 
     System.out.print(this.num + comma); 
     testEvenOdd(); 
     } 
    } 
} 

UPDATE

因爲自從實例變量使用我已經更新了你的方法參數,也沒有必要通過num作爲參數傳遞給ifEvenifOdd。這將消除您當前擁有的錯誤。另請注意,由於我們不再具有與實例變量同名的方法參數,因此我們不再需要this關鍵字。但是,我留下了他們的良好做法。

+0

玩魔鬼主張,爲什麼要將'int num'傳遞給那些開始的方法? –

+0

@OusmaneDiaw因爲使用實例變量,沒有必要通過'num'作爲參數傳遞給'ifEven'和'ifOdd'(我想這是艾略特告訴過) – BackSlash

+0

@BackSlash正確的I看到他是在得到。我應該更新我的答案以適應這些建議。 –

0

如果您的輸入是7,22是正確的輸出!

testEvenOdd()轉到else語句,即ifOdd(7)。在這裏,因爲7不是1,所以你正在打印(7 * 3)+ 1 = 22。然後你再次調用testEvenOdd()!因此,它將ifOdd(7),打印出22,並再次調用testEvenOdd()。它很可能無限期地重複,直到你用完內存。

0

你以哪種順序調用這些方法?我會想你打電話start()然後testEvenOdd()

如果您輸入7,在方法內部testEvenOddif((num % 2) == 0)會是假的(因爲7 % 2爲1)。因此,它會調用方法ifOdd()

ifOdd方法,爲num是7,if(num == 1)會是假的,它會調用else條款:num = (num * 3) +1,所以num將是22 - >的(7 * 3的結果)+ 1