我正在为课程做一个项目,在这个项目中,你必须制作一个名人堂,并能够添加/删除/搜索/编辑不同种类的乐队。现在,我在搜索特定波段的索引时遇到了问题,因为它总是返回-1,而我不确定为什么。
下面是我的代码:
public class HallofFame
{
public static ArrayList<Band> hallOfFame = new ArrayList<Band>();
public static Scanner scan = new Scanner(System.in);
public static void main(String[]args){
int a = 0;
while(a == 0){
System.out.println("What would you like to do?");
System.out.println("");
System.out.println("1. Add");
System.out.println("2. Remove");
System.out.println("3. Edit");
System.out.println("4. Clear");
System.out.println("5. Search");
System.out.println("6. Quit");
System.out.println("");
String choice = scan.nextLine();
if(choice.equals ("1")){
add();
}
else if(choice.equals ("2")){
remove();
}
else if(choice.equals ("3")){
edit();
}
else if(choice.equals ("4")){
clear();
}
else if(choice.equals ("5")){
search();
}
else if(choice.equals ("6")){
quit();
break;
}
}
}
public static void add(){
Scanner booblean = new Scanner(System.in);
System.out.println("What is the name of the band you would like to add?");
String name = scan.nextLine();
System.out.println("What kind of genre is this band?");
String genre = scan.nextLine();
System.out.println("How many members are in the band?");
int numMem = scan.nextInt();
System.out.println("How many songs does this band have?");
int numSongs = scan.nextInt();
System.out.println("How many albums does this band have?");
int numAlbs = scan.nextInt();
System.out.println("Is this band currently active?");
String yesno = booblean.nextLine();
boolean isActive = false;
if(yesno.equalsIgnoreCase ("yes")){
isActive = true;
}
Band b1 = new Band(name, genre, numMem, numSongs, numAlbs, isActive);
hallOfFame.add(b1);
System.out.println("");
System.out.println("The band " + name + " has been added to the database.");
System.out.println("");
}
public static void remove(){
}
public static void edit(){
System.out.println("What band info do you want to edit?");
String searchband = scan.nextLine();
}
public static void clear(){
hallOfFame.clear();
}
public static void search(){
System.out.println("What band name are you searching for?");
String searchband = scan.nextLine();
int retval = hallOfFame.indexOf(searchband);
System.out.println("The band " + searchband + " is at index: " + retval);
}
public static void quit(){
System.exit(0);
}
}搜索方法是我遇到问题的方法。
发布于 2013-11-12 07:50:42
问题是hallOfFame包含Band对象,而您在hallOfFame中搜索String。相反,您可以遍历hallOfFame并将乐队名称与输入的字符串进行比较。
发布于 2013-11-12 07:55:28
或者,您可以覆盖Band的equals方法,这样indexOf就可以实际工作了。
我想它应该是这样的:
@Override
public boolean equals(Object o) {
return ((Band) o).name==this.name;
}发布于 2013-11-12 10:53:17
您应该同时覆盖equals和hashCode,以使其完美工作。
https://stackoverflow.com/questions/19917985
复制相似问题