2016-09-20 72 views
-1

我已經寫了一個函數類來獲取最大輸入作爲輸出,但結果是錯誤的。我不知道爲什麼,下面是我的代碼:計算最大值時出現錯誤結果

public class Test { 
    public int max(int a, int b) { 
     if(a > b) 
      return a; 
     else { 
      swap(a, b); 
      return a; 
     } 
    } 

    private void swap(int a, int b) { 
     // TODO Auto-generated method stub 
     int tmp = a; 
     a = b; 
     b = tmp; 
    } 

    public static void main(String[] args) { 
     Test t = new Test(); 
     int max = t.max(3, 6); 
     System.out.println(max); 
    } 
} 

在這種情況下,我的結果是3而不是6

+0

的JavaScript不是Java。 – Li357

+3

請參閱:http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value?rq=1以及爲什麼您需要交換方法? – Li357

+0

我想要一個最大值 – Jingwei

回答

0

@Jingwei爲什麼喲具有交換功能?

要獲得的2個整數以下max是程序

public class Test { 
    public int max(int a,int b) 
    { 
     if(a > b) 
      return a; 
     else 
      return b; 
    } 

    public static void main(String [] args) 
    { 
     Test t = new Test(); 
     int max = t.max(3, 6); 
     System.out.println(max); 
    } 
} 
+0

我想要一個最大值。實際上,我的問題是爲什麼swap()不起作用? – Jingwei

+0

Swap()不交換變量,但傳遞變量的副本,但不傳遞指針。那是因爲你沒有爲整個班級使用靜態變量。聲明'a'作爲類的變量,然後你的交換應該工作。我可以寫一個樣本。 – talisman027

+0

你是什麼意思:Swap()不交換變量,但變量的副本被傳遞,你沒有傳遞指針。 – Jingwei