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

Incompatible types: java.lang.String cannot be converted to boolean

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

incompatible types: java.lang.String cannot be converted to boolean

当您 运行 getName 方法时,它应该检查用户输入的条形码,如果匹配,它将 return 一个字符串。

这是我正在执行方法调用的 class 和方法。

public class ItemTable

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

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

    return name;
   }

我是method/class打来的。

public class Item

private String barcode;

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

public String getBarcode (String barcode)
{
    return barcode;
}
if (x.getBarcode ("00001")) 

如果仔细观察,if 旁边必须有一个 boolean 值来检查 truefalse。你的方法返回 String.

条件需要布尔值才能运行。因此,插入 returns 字符串的方法将不起作用。您需要将“00001”与另一个字符串进行比较,以使条件适用于您的情况。

要解决此问题,需要对字符串进行比较。 所以...

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

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

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

public String getBarcode()
{
return barcode;
}

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