我有一个类型为Store的列表,用户可以在列表中添加项目,其中包含与它们相关联的名称和ID。在列表中搜索提供了错误的结果
public class StoreSearch {
public static void main(String[] args) throws IOException {
ArrayList <Store> stores = new ArrayList();
String input = "";
String name;
int id = 0;
int newId = 0;
int index = 0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while(!(input.equals("quit"))) {
System.out.println("Hello!\nEnter add or search");
input = in.readLine();
if(input.equalsIgnoreCase("add")) {
System.out.println("Enter a name ");
name = in.readLine();
System.out.println("Enter a id");
input = in.readLine();
id = Integer.parseInt(input);
Store s = new Store(name,id);
if(!stores.contains(s))
stores.add(s);//only add if combination of name and id are not in it
}
if(input.equals("search")) {
System.out.println("Enter a name");
name = in.readLine();
System.out.println("Enter a id guideline");
input = in.readLine();
index = input.indexOf("-");
if(index == 0) {
String substring = input.substring(input.lastIndexOf("-") + 1);
newId = Integer.parseInt(substring);
Store s = new Store(name,id);
for(int counter = 0; counter < stores.size(); counter++) {
if(stores.contains(s)) {
System.out.println(stores.toString());
}
}
}
if(index == 4) {
String[] parts = input.split("\\-"); // String array, each element is text between dots
newId = Integer.parseInt(parts[0]);
//the hyphen after the 4 digit number
}
else {
//only id
}
}
}
}
}
和存储类:
public class Store {
private String name;
private int id;
public Store(String name, int id) {
this.name = name;
this.id = id;
}
@Override
public String toString() {
return " Name " + name + " id " + id;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Store){
Store element = (Store) obj;
if(this.name.equals(element.name) && element.id == (this.id)){
return true;
}
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = 61 * hash + Objects.hashCode(this.name);
hash = 61 * hash + this.id;
return hash;
}
}
我有添加到列表中,在那里我如果的事的组合进入我只添加到列表中没有任何问题,它的名称和ID不存在已经存在。然而,我试图搜索列表,这导致了我的问题。
举例来说,如果我已经添加了这些元素的列表:
Snack 3366
Apple 3367
Apple 3368
,我想搜索列表如下:
名称为“苹果” 标识准则是本"-3368"
意义,应该打印出任何具有相同名称并具有3368以前的对象的对象。但是,我的输出从来不会这样做。我尝试使用stores.get(index);
打印出来,但仍然给我错误的输出。
对于第二条if语句,它检查它们是否是4位数字后面的连字符,在这种情况下,“3370-”意味着所有输入名称的对象,并且应该返回id 3370及以上。考虑到我无法弄清楚第一个陈述,我无法尝试第二个陈述。任何帮助,将不胜感激。
'如果(OBJ的instanceof书){'?你什么时候到要比较一个'Book'反对'Store'?另外,你可以使用'Set'而不是'List'来保证不安全 – MadProgrammer
对不起,我只是修复了它,我也被迫使用了arrayL为此。 – user3739406
为什么if(stores.contains(s)){'在for循环中?你不使用'counter'。 –