无法解析为变量 (Java)
Cannot be resolved as a variable (Java)
我正在编写一个程序,允许用户从狗窝登记狗,我正在尝试创建一个搜索函数,循环遍历数组列表 "dogs",然后打印出狗的名字(如果存在),如果不存在,则会打印出错误。
声明的变量:
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;
}
和主要的搜索方法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);
}
}
我收到以下错误:
Dog result = null;
return result;
其中指出:
result cannot be resolved to a variable.
有人能给我解释一下吗?我是 Java 的新手,所以我非常迷茫。
谢谢。
您正试图通过调用 equals
将 result
赋给 search
方法中 searchedFor
的值,实际上 return boolean
如果 x
等于 argument
。
改用=
赋值。
或者直接returnsearchedFor
!
result.equals(已搜索);
是条件遗漏and语句还是赋值语句?
如果赋值语句应该是
结果 = searchedFor
你可以这样做:
if(searchedFor != null)
result = searchedFor
而不是:
result.equals(searchedFor);
我正在编写一个程序,允许用户从狗窝登记狗,我正在尝试创建一个搜索函数,循环遍历数组列表 "dogs",然后打印出狗的名字(如果存在),如果不存在,则会打印出错误。
声明的变量:
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;
}
和主要的搜索方法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);
}
}
我收到以下错误:
Dog result = null;
return result;
其中指出:
result cannot be resolved to a variable.
有人能给我解释一下吗?我是 Java 的新手,所以我非常迷茫。
谢谢。
您正试图通过调用 equals
将 result
赋给 search
方法中 searchedFor
的值,实际上 return boolean
如果 x
等于 argument
。
改用=
赋值。
或者直接returnsearchedFor
!
result.equals(已搜索);
是条件遗漏and语句还是赋值语句?
如果赋值语句应该是
结果 = searchedFor
你可以这样做:
if(searchedFor != null)
result = searchedFor
而不是:
result.equals(searchedFor);