不兼容的类型:java.lang.String无法转换为boolean

时间:2016-05-01 00:41:30

标签: java syntax bluej

我试图在if语句中调用一个方法但是我一直收到以下错误。

  

不兼容的类型:java.lang.String无法转换为boolean

运行getName方法时,应检查用户输入的条形码,如果匹配,则返回String。

这是我正在进行方法调用的类和方法。

public class ItemTable

   public String getName (Item x)
   {
    String name = null;

    if (x.getBarcode ("00001")) 
        name = "Bread";

    return name;
   }

这是我调用的方法/类。

public class Item

private String barcode;

public Item (String pBarcode)
{
    barcode = pBarcode;
}

public String getBarcode (String barcode)
{
    return barcode;
}

3 个答案:

答案 0 :(得分:3)

if (x.getBarcode ("00001")) 

如果您近距离查看if,则必须在boolean一侧检查truefalse。您的方法返回String的位置。

答案 1 :(得分:0)

条件需要布尔运算。因此,插入返回String的方法将不起作用。你需要比较" 00001"使用另一个String来获取条件以适用于您的情况。

要修复此问题,需要比较字符串的比较。 所以......

if(x.getBarcode("00001").equals("00001")) //equals returns a boolean if the strings are the same.
{
    name = "bread";
}

您还应该使用this.barcode指定是否要在参数或私有变量条形码中返回条形码。

答案 2 :(得分:0)

我从未见过接收参数的getter方法。 getBarcode方法应该返回Item对象的实际条形码,对吧?您发送给构造函数方法的那个。 如果您对上述问题的回答是肯定的,那么getBarcode方法不需要参数,if应该被修改,例如:

public String getBarcode()
{
return barcode;
}

并且

if(x.getBarcode().equals("00001"))
    name = "Bread";
相关问题