程序打印出对数组中每个字符的响应,只要发现或不找到该值就只需要打印即可

时间:2019-03-08 01:07:09

标签: java arrays

import java.util.Scanner;

public class Array1{

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int[] values = {1, 2, 3, 4, 5};

        System.out.println("Please enter an integer:");

        int userInput = input.nextInt();

        for (int i = 0; i < values.length; i++) {
            if (values[i] == userInput) {

                System.out.println("value found!");
            } else {
                System.out.println("value not found!");
            }
        }
    }
}

所以可以说用户输入3,我希望它打印出一次找到的值,但是它打印出来,或者如果用户输入数字而不是它的数组,我希望它说一次找不到的值而不是针对数组中的每个数字重复它。我只想比较用户输入的数字,看看是否能在数组中找到它。

value not found!
value not found!
value found!
value not found!
value not found!

2 个答案:

答案 0 :(得分:1)

我能想到的最简单的解决方案是使用标志。

boolean found = false;
for (int i = 0; i < values.length; i++) {
    if(values[i] == userInput) {
        found = true;
        break;    // can end the loop since value was found
    }
}

if(found) {
    System.out.println("value found!");
} else {
    System.out.println("value not found!");
}

答案 1 :(得分:1)

看到这种情况的原因是,您在循环的每次迭代中都打印出if语句的结果。

相反,您要做的是在循环之前设置一个boolean值,如果找到该值,则将其设置为true

然后, 循环结束后,您可以检查是否将boolean设置为true

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    int[] values = {1, 2, 3, 4, 5};

    System.out.println("Please enter an integer:");

    int userInput = input.nextInt();

    boolean valueFound = false;
    for (int i = 0; i < values.length; i++) {
        if (values[i] == userInput) valueFound = true;
    }

    if (valueFound) {
        System.out.println("Value Found!");
    } else {
        System.out.println("Value NOT Found!");
    }
}

结果:

Please enter an integer:
3
Value Found!