无法解析为变量(Java)

时间:2015-04-08 15:46:27

标签: java variables

我正在编写一个程序,允许用户从狗窝检入和检出狗,我正在尝试创建一个搜索功能,循环遍历数组列表“狗”,然后打印出狗的名字如果存在,如果没有,则会打印出错误。

声明变量:

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

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

主类中的搜索方法(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);
    }
}

我收到错误:

Dog result = null;
return result;

指出:

result cannot be resolved to a variable.

有人能解释一下吗?我是Java的新手,所以我非常迷失。

感谢。

3 个答案:

答案 0 :(得分:3)

您正试图通过调用resultsearchedFor分配给search方法中equals的值,boolean实际返回x if {{ 1}}等于argument

使用=代替分配。

或直接返回searchedFor

答案 1 :(得分:0)

result.equals(searchedFor);

这是一个错过的条件和陈述或转让声明吗?

如果是assign语句,那么它应该是

result = searchingFor

答案 2 :(得分:0)

你可以这样做:

if(searchedFor != null)
  result = searchedFor   

而不是:

result.equals(searchedFor);