You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断输入数字是否在Java数组中?现有代码匹配逻辑异常

问题根因

你的代码逻辑错误出在循环内的else if分支:每次遍历到不匹配的元素时,都会把yon重新覆盖为0。比如你输入3,遍历到索引2的元素时确实把yon设为1,但后续遍历索引3到9的元素时,因为都不匹配,每次都会把yon改回0,最终循环结束后yon永远是最后一个元素的匹配结果,自然不符合预期。

修复方案

两种常用修复方式可选:

方式1:匹配成功后直接跳出循环

去掉多余的else if分支,匹配到目标值后直接终止循环,避免后续遍历覆盖yon的取值:

int yon = 0;
int[] newNums = {1,2,3,4,5,6,7,8,9,10};
System.out.print("Enter a number:");
int userNum = scan.nextInt();
for (int i = 0; i<newNums.length; i++){
  if (userNum == newNums[i]){
    yon = 1;
    // 匹配到直接结束循环,不需要继续遍历
    break;
  }
}
if (yon==1){
  System.out.println("That number was in the array.");
}else{
  System.out.println("That number was not in the array.");
}

方式2:移除else分支

如果不想用break,也可以直接删除循环内的else if逻辑,初始值设为0,只有匹配到才修改为1即可:

int yon = 0;
int[] newNums = {1,2,3,4,5,6,7,8,9,10};
System.out.print("Enter a number:");
int userNum = scan.nextInt();
for (int i = 0; i<newNums.length; i++){
  if (userNum == newNums[i]){
    yon = 1;
  }
}
if (yon==1){
  System.out.println("That number was in the array.");
}else{
  System.out.println("That number was not in the array.");
}

内容的提问来源于stack exchange,提问作者rabbi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 05:24:05