我有一个练习,涉及到“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){
我不知道我做错了什么,它是唯一的出现错误。
你为什么要检查int与instanceof? – ravi
'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
新生学习Java的提示:不要认为你还没有完全研究过的概念......是“好的”,因为“它们看起来很好”。在编程中,没有看起来很好的东西。编译器是确定性的;他们分析源代码;当一个编译器给你一个错误信息时,那么好看并不重要。在这种情况下,要做的事情是仔细阅读错误信息,并可能会打开一本书,并研究指出将更详细地使用错误的概念。 – GhostCat