我必须从用户输入中比较字符串和字符串数组,但是我遇到了逻辑错误,即使用户输入了数组中的字符串,输出仍会显示“找不到数据”。如果用户要比较的字符串在数组中,我还必须提到数组的索引,但是我也遇到了错误。请帮助我,以下是我尝试执行的代码。 [错误输出] [1]
package stringsearch;
import java.util.Scanner;
public class StringSearch
{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
String [] names = new String[5];
for (i = 0; i < names.length; i++)
{
System.out.print("Enter name " + (i + 1) + " > ");
names[i] = sc.nextLine();
}
System.out.print("Input Name to compare > ");
String inName = sc.nextLine();
if (names.equals(inName)){
System.out.println("Data found at ["+i+"]");
}
else
{
System.out.println("Data not found!");
}
}
}
[1]: https://i.stack.imgur.com/BnVEc.png
您正在将整个数组与单个字符串进行比较,该字符串将始终返回false。
与以下相同:
String[] names = {"a", "b", "c"};
names.equals("d");
迭代数组以查看是否存在字符串
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
return i;
}
i++
}
if (i == names.length ) {
// not found
}
运行示例:
public class A {
public static void main(String...args){
String[] names = {"a", "b", "c"};
String inName = "d";
int i = 0;
for (String item: names) {
if (item.equals(inName) ) {
System.out.println(i);
break;
//return i;
}
i++;
}
if (i == names.length ) {
System.out.println(-1);
// not found
}
}
}