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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36961797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 02:03:17  来源:igfitidea点击:

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

javasyntaxbluej

提问by Ayden Brownhill

I am trying to call a method within an if statement but I keep getting the following error.

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

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

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

When you run the getName method it should check the barcode the user enters and if it matches, it will return a String.

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

This is the class and method I am doing the method call.

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

public class ItemTable

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

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

    return name;
   }

This is the method/class I am calling from.

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

public class Item

private String barcode;

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

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

回答by Suresh Atta

if (x.getBarcode ("00001")) 

If you look close ifmust have a booleanvalue in side to check trueor false. Where your method returning String.

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

回答by DarkV1

A conditional requires a boolean to operate. Thus, inserting a method that returns a String will not work. You need to compare the "00001" with another String to get the conditional to work in your case.

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

To Fix this problem a comparison that compares a string is needed. so ...

为了解决这个问题,需要一个比较字符串的比较。所以 ...

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

You should also use this.barcode to specify if you want to return the barcode in the parameters or the private variable, barcode.

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

回答by Jorge Solis

I've never seen a getter method receiving parameters. The getBarcode method should return the actual barcode of your Item object, right? The one you send to the constructor method. If your answer to above question is yes, then the getBarcode method needs no arguments and the if should be modified, example:

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

public String getBarcode()
{
return barcode;
}

And

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