未在数组中找到字符串值

Not found string value on array

我是 java 的初学者。

为什么总是显示找不到?

以及如何在数组上创建一个未找到的字符串值?

    String[] array = new String[10];
    String b = "5";
    for (int i = 0; i < 10; i++) {
        String in = String.valueOf(i);
        array[i] = in;
    }
    for (int i = 0; i < 10; i++) {
        if (b.equals(array[i])) {
            System.out.println("found " + array[i]);
        } else if (!b.equals(array[i])) {
            System.out.println("not found");
            System.exit(0);
        }
    }
}

当您调用 System.exit(0); 时,您的第二个 for 循环在 i = 0 处终止(程序实际上在您调用时整体终止)。

} else if (!b.equals(array[i])) {
    System.out.println("not found");
    System.exit(0);
}

建议将逻辑更改为 在找到匹配项时从循环中中断

for (int i = 0; i < 10; i++) {
  if (b.equals(array[i])) {
     System.out.println("found " + array[i]);
     break;
  }
}

好的,我已经弄清楚了。

感谢您的建议。

只需在循环外创建 "not found" 语句。

String[] array = new String[10];
    String b = "10";
    boolean c = false;
    for (int i = 0; i < 10; i++) {
        String in = String.valueOf(i);
        array[i] = in;
    }
    for (int i = 0; i < 10; i++) {
        if (b.equals(array[i])) {
            System.out.println("found " + array[i]);
        } else if (!b.equals(array[i])) {
            c = true;
            }
    }
    if (c == true){
        System.out.println("not found");
    }
}