gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 17:59:29 26 4
gpt4 key购买 nike

我对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;
}
}
}
}

最佳答案

要解决您的问题,您只需删除数组的 else 部分中使用的 has 即可。考虑这样的情况

例如。 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");
}
}
}

关于java - 如何检查某些数字是否出现在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42182386/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com