简体   繁体   English

无法解析为变量(Java)

[英]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. 我正在编写一个程序,允许用户从狗窝中签入和签出狗,并且正在尝试创建一个搜索功能,该功能遍历数组列表“ dogs”,然后打印出狗的名称(如果存在) ,如果没有,则会打印出错误。

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() : 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()): 以及主类中的搜索方法(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. 我是Java的新手,所以我很迷路。

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 . 您正在尝试通过调用equalsresult分配给您的search方法中searchedFor的值,如果x equals argument实际上返回boolean

Use = to assign instead. 使用=代替。

Or return searchedFor directly! 或直接返回searchedFor

result.equals(searchedFor); result.equals(searchedFor);

Is it a condition missing out and statements or an assign statement? 它是条件缺失和声明还是assign语句?

If assign statement it should be 如果赋值语句应该是

result = searchedFor 结果= searchedFor

You can do this: 你可以这样做:

if(searchedFor != null)
  result = searchedFor   

instead of: 代替:

result.equals(searchedFor);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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