2015-10-17 81 views
-1

我有一個練習,涉及到「instanceof」,我不太清楚如何使用它。這是我想出了:語法錯誤的實例?

for(int i = 4; i < 6; i++){ 
    int availSupply = part[i].stockLevel+part[i].getAvailForAssembly(); 
    if(availSupply instanceof Integer){ 
     System.out.println("Total number of items that can be supplied for "+ part[i].getID()+"(" + part[i].getName() + ": "+ availSupply); 
    } 
} 

代碼看起來沒什麼問題,但它想出了一個錯誤:

Multiple markers at this line 

Incompatible conditional operand types int and Integer at: if(availSupply instanceof Integer){ 

我不知道我做錯了什麼,它是唯一的出現錯誤。

+0

你爲什麼要檢查int與instanceof? – ravi

+0

'int'是一個原始數據類型,而Integer是一個類。 'instanceof'運算符不適用於原始數據類型。你應該將'availSupply'變量聲明爲Integer。 [原始數據類型](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html)[Java包裝類](http://www.w3resource.com/java-tutorial/java- wrapper-classes.php) – AndrewMcCoist

+2

新生學習Java的提示:不要認爲你還沒有完全研究過的概念......是「好的」,因爲「它們看起來很好」。在編程中,沒有看起來很好的東西。編譯器是確定性的;他們分析源代碼;當一個編譯器給你一個錯誤信息時,那麼好看並不重要。在這種情況下,要做的事情是仔細閱讀錯誤信息,並可能會打開一本書,並研究指出將更詳細地使用錯誤的概念。 – GhostCat

回答

8

您不能使用instanceof表達基本類型,就像您在這裏使用availSupply一樣。畢竟,int不可能是別的。

如果getAvailForAssembly()已聲明爲返回int,那麼根本不需要您的if語句 - 只是無條件地執行主體。如果返回Integer,你應該使用:

Integer availSupply = ...; 
if (availSupply != null) { 
    ... 
} 
0

這裏int是一種原始值和對象instanceof關鍵字檢查屬於你的情況,我的類,電子Integer。所以int本身就是一個原始值是不a instance of classInteger 以下是instanceof的基本片段關於使用它的關鍵字。

class InstanceofDemo { 
    public static void main(String[] args) { 

     Parent obj1 = new Parent(); 
     Parent obj2 = new Child(); 

     System.out.println("obj1 instanceof Parent: " 
      + (obj1 instanceof Parent)); 
     System.out.println("obj1 instanceof Child: " 
      + (obj1 instanceof Child)); 
     System.out.println("obj1 instanceof MyInterface: " 
      + (obj1 instanceof MyInterface)); 
     System.out.println("obj2 instanceof Parent: " 
      + (obj2 instanceof Parent)); 
     System.out.println("obj2 instanceof Child: " 
      + (obj2 instanceof Child)); 
     System.out.println("obj2 instanceof MyInterface: " 
      + (obj2 instanceof MyInterface)); 
    } 
} 

class Parent {} 
class Child extends Parent implements MyInterface {} 
interface MyInterface {} 

輸出:

obj1 instanceof Parent: true 
    obj1 instanceof Child: false 
    obj1 instanceof MyInterface: false 
    obj2 instanceof Parent: true 
    obj2 instanceof Child: true 
    obj2 instanceof MyInterface: true 

請到通過這個環節更好地理解instanceof關鍵字: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html

0

你不能用基本類型的變量使用instanceof操作符(如int,booleanfloat),因爲他們可以在ly包含它們的名稱已經告訴您的數字/值(整數爲int,truefalseboolean和浮點數爲float)。

變量的類型是類,但是,可以使用instanceof,因爲類可以(通常)被擴展。變量Foo variable也可能包含類Bar的一個實例(例如,如果Bar extends Foo),所以您可能實際上在此處需要instanceof運算符。