我想要一个程序,它接受字符串作为输入,而不是从漫画[k]中搜索特定单词,并在漫画[k] []处打印字符串。这是代码
Scanner s=new Scanner(System.in);
String str;
int k=0;
String[][] cartoons = {
{ "Flintstones", "Fred is a bad boy."},
{ "Rubbles", "Barney rocks."},
{ "Jetsons", "George was president of America."},
{ "Scooby Doo Gang", "Scooby Doo where are you?"} };
boolean found=false;
for (int i = 0; i < cartoons.length; i++) {
System.out.print(cartoons[i][0] + ": ");
for (int j = 1; j < cartoons[i].length; j++) {
System.out.print(cartoons[i][j] + " ");
}
System.out.println();
}
System.out.println("Enter name to search.");
str=s.nextLine();
while(k<cartoons.length){
if(str.equals(cartoons[k])){
System.out.print(cartoons[k]);
found=true;
}
k++;
}
System.out.println("Not found");
}
答案 0 :(得分:0)
分别使用cartoons[k][0]
和cartoons[k][1]
。 String
的数组不是String
。将数组作为参数,String::equals
将始终为false。我还修复了下面的循环退出条件:
Scanner s=new Scanner(System.in);
String str;
int k=0;
String[][] cartoons = {
{ "Flintstones", "Fred is a bad boy."},
{ "Rubbles", "Barney rocks."},
{ "Jetsons", "George was president of America."},
{ "Scooby Doo Gang", "Scooby Doo where are you?"} };
boolean found=false;
for (int i = 0; i < cartoons.length; i++) {
System.out.print(cartoons[i][0] + ": ");
for (int j = 1; j < cartoons[i].length; j++) {
System.out.print(cartoons[i][j] + " ");
}
System.out.println();
}
System.out.println("Enter name to search.");
str=s.nextLine();
while(!found && k<cartoons.length){
if(str.equals(cartoons[k][0])){
System.out.print(cartoons[k][1]);
found=true;
}
k++;
}
if (!found) {
System.out.println("Not found");
}