2015-10-17 59 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运算符。