简体   繁体   中英

Cannot be resolved as a variable (Java)

I'm writing a program which allows a user to check in and out dogs from a kennel and I'm trying to create a search function that cycles through the array list "dogs" and then print out the name of the dog if it exists, if not you get an error printed out.

Declared variables:

public class Kennel {
private String name;
private ArrayList<Dog> dogs;
private int nextFreeLocation;
private int capacity;
private String result;

Code for the search function in Kennel() :

    public Dog search(String name) {
    Dog searchedFor = null;
    // Search for the dog by name
    for (Dog d : dogs) {
        if (name.equals(d.getName())) {
            searchedFor = d;
        }
    }
    /*
    if (searchedFor != null) {
        dogs.remove(searchedFor); // Requires that Dog has an equals method
        System.out.println("removed " + name);
        nextFreeLocation = nextFreeLocation - 1;
    } else
        System.err.println("cannot remove - not in kennel");
    Dog result = null;*/

    Dog result = null;

    result.equals(searchedFor);

    return result;
}

And the search method in the main class (KennelDemo()):

    private void searchForDog() {
    System.out.println("which dog do you want to search for");
    String name = scan.nextLine();
    Dog dog = kennel.search(name);
    if (dog != null){
        System.out.println(dog.toString());
    } else {
        System.out.println("Could not find dog: " + name);
    }
}

I'm getting the error for:

Dog result = null;
return result;

which states:

result cannot be resolved to a variable.

Can anyone explain this to me please? I'm new to Java so I'm extremely lost.

Thanks.

You are trying to assign result to the value of searchedFor in your search method, through invoking equals , which actually return boolean if x equals argument .

Use = to assign instead.

Or return searchedFor directly!

result.equals(searchedFor);

Is it a condition missing out and statements or an assign statement?

If assign statement it should be

result = searchedFor

You can do this:

if(searchedFor != null)
  result = searchedFor   

instead of:

result.equals(searchedFor);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM