如何检查某些数字是否出现在数组中?

时间:2017-02-11 23:19:55

标签: java arrays if-statement for-loop

我对java比较新。我试图找出是否存储了0到4的数字 在大小为5的数组中的某个位置。用户输入0-4之间的整数来填充数组。我已经成功地设法让它确认用户输入的第一个数字是在数组中,然后是没有出现的数字。 例如:如果用户输入数字2,2,2,1,3我将只得到数组中的2个。

public static void checkEachNumber(int[] array)
{
    int currentNum = 0;
    for(int i = 0; i < array.length; i++)
    {
        for(int j = 0; j < array.length; j++)
        {
            currentNum = i;
            if(currentNum == array[j])
            {
                System.out.println(currentNum + " appears in the array");
                break;
            }
            else
            {
                System.out.println(currentNum + " doesn't appear in the array");
                break;
            }
        }
    }
}

2 个答案:

答案 0 :(得分:2)

执行break语句时,循环将完全停止运行。通常,扫描匹配的方式如下所示:

found_match = no

for (... in ...) {
    if (match) {
        found_match = yes
        break
    } 
}

if (found_match) {
    do_found_match_stuff();
}

答案 1 :(得分:2)

要解决您的问题,您应该只删除数组的else部分中使用的。 考虑像这样的案例

离。 2 1 4 3

当检查i = 1时,它将首先将该值与2进行比较,以便它离开循环。

public static void checkEachNumber(int[] array)
{
    int currentNum = 0;
    for(int i = 0; i < array.length; i++)
    {
        int flag=0;
        for(int j = 0; j < array.length; j++)
        {
            currentNum = i;
            if(currentNum == array[j])
            {
                System.out.println(currentNum + " appears in the array");
                flag=1;
                break;
            }

        }
        if(flag==0)
        {
              System.out.println("currentNum+"Doesn't appear in array");
        }
    }
}
相关问题