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

Java 如何检查数组中是否出现某些数字?,java,arrays,if-statement,for-loop,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.leng

我对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;
            }
        }
    }
}
publicstaticvoidcheckeachnumber(int[]数组)
{
int currentNum=0;
for(int i=0;i
执行
break
语句时,循环完全停止运行。通常,扫描匹配项的方式如下所示:

found_match = no

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

if (found_match) {
    do_found_match_stuff();
}

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

found_match = no

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

if (found_match) {
    do_found_match_stuff();
}

要解决您的问题,您只需删除阵列的else部分中使用的have。 考虑这样一个例子

例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");
        }
    }
}
publicstaticvoidcheckeachnumber(int[]数组)
{
int currentNum=0;
for(int i=0;i
要解决您的问题,您只需删除阵列的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");
        }
    }
}
publicstaticvoidcheckeachnumber(int[]数组)
{
int currentNum=0;
for(int i=0;i
哦,好的。我确实怀疑问题出在break语句上。哦,好吧。我确实怀疑问题出在break语句上。