0

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

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

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

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

3 Answers 3

3
if (x.getBarcode ("00001")) 

If you look close if must have a boolean value in side to check true or false. Where your method returning String.

Sign up to request clarification or add additional context in comments.

Comments

0

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:

public String getBarcode()
{
return barcode;
}

And

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

Comments

0

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.

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.