【问题标题】:Incompatible types: java.lang.String cannot be converted to boolean不兼容的类型:java.lang.String 无法转换为布尔值
【发布时间】:2016-08-25 23:59:33
【问题描述】:

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

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

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

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

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;
}

【问题讨论】:

    标签: java syntax bluej


    【解决方案1】:
    if (x.getBarcode ("00001")) 
    

    如果您仔细观察if,则必须在旁边有一个boolean 值才能检查truefalse。你的方法在哪里返回String

    【讨论】:

      【解决方案2】:

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

      public String getBarcode()
      {
      return barcode;
      }
      

      还有

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

      【讨论】:

        【解决方案3】:

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

        要解决此问题,需要比较字符串。 所以……

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

        还应该使用this.barcode来指定是返回参数中的条形码还是私有变量barcode。

        【讨论】:

          猜你喜欢
          • 2017-10-03
          • 2017-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-12
          • 1970-01-01
          • 2019-07-07
          • 1970-01-01
          相关资源
          最近更新 更多