2014-12-05 48 views
0
public static int getComputerMoveAI(int left) 
{ 
    Integer returnValue = 0; 
    Integer place = nimMachine.size() - left; 
    returnValue = nimMachine.get(place).get(((int)Math.random()*place)+1); 
    plays[place] = returnValue; 
    return intValue(returnValue); 
} 

我希望我的程序返回一個int值,以便main可以使用該值,但我不明白如何使發生。我知道這是不正確的,但我把我想要將整數更改爲int。我必須使用Integer作爲我的數組列表。我不明白如何讓我的程序從一個整數返回int值

+0

你想'returnValue.intValue()'。 – APerson 2014-12-05 04:41:23

+0

可能重複[如何將Integer轉換爲int?](http://stackoverflow.com/questions/3571352/how-to-convert-integer-to-int) – durron597 2015-04-01 15:35:23

回答

2

Integerint將根據系統需要自動從一個更改爲另一個。這就是所謂的autoboxing

這可以看作詮釋他下面的代碼:

class Ideone { 
    public static int foo() { 
     Integer rv = Integer.valueOf(42); 
     return rv; 
    } 

    public static Integer bar() { 
     int rv = 42; 
     return rv; 
    } 

    public static void main (String[] args) { 
     System.out.println(foo()); 
     System.out.println(bar()); 
    } 
} 

ideone

此打印出42和42。但需要注意的是,在foo()rvIntegerbar()這是一個int - 每個返回值的「錯誤」類型。

這到底是怎麼回事的是,intbar()foo()得到轉化爲Integer,該Integer是越來越通過裝箱和拆箱的過程轉化爲int爲您服務。

在這種情況下,您不需要執行returnValue.intValue()Integer.valueOf(someInt)或任何其他方法調用來將一個轉換爲另一個。讓系統爲你做。它會工作。

+0

特別是因爲Integer.intValue(someInteger)不存在:) – 2014-12-05 04:49:06

+0

@MrZorn多數民衆贊成什麼,我得到這麼晚做事情。當我真的想要兩種不同的方法示例時,我將兩種方法混合在一起。 – 2014-12-05 04:51:15

+0

如果它讓你感覺更好,我開始寫出像你解釋自動裝箱的答案,但決定以最簡單的方式回答這個問題,因爲在這麼晚的時候懶惰。所以對你的徹底的答案很感謝。 – 2014-12-05 04:53:32

相關問題