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

Java数组含指定值检测程序问题求助:代码无法运行

解决数组包含指定值的检测问题

你的代码存在几个关键问题导致无法正常运行,下面逐一说明并给出修正方案:

问题分析

  • 多余的无效判断:if ( num [i] == x );这行完全没用,分号让if没有执行体,而且你刚把x赋值给num[i],这个判断毫无意义,直接删掉即可。
  • 数组越界错误:循环结束后,变量i的值等于数组长度(比如数组大小为4,循环结束后i=4),但数组索引范围是0到size-1,此时访问num[i]会直接抛出数组越界异常。
  • 未正确遍历查找目标:你没有遍历整个数组检查每个元素是否匹配搜索值,仅用循环结束后的无效索引做判断,逻辑完全错误。

修正后的代码

import java.util.Scanner;

public class ArraySearch {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int i;
        System.out.print("Input the size of the array: ");
        int size = input.nextInt(); 
        int num[] = new int[size];  

        System.out.println("Enter " + size + " values:");
        for(i = 0; i < num.length; i++){ 
            num[i] = input.nextInt();
        }

        System.out.print("Enter the search value: ");
        int search = input.nextInt();
        
        // 用布尔变量标记是否找到目标值
        boolean isFound = false;
        for(i = 0; i < num.length; i++){
            if(num[i] == search){
                isFound = true;
                break; // 找到后直接跳出循环,减少不必要的遍历
            }
        }

        if(isFound){
            System.out.println(search + " is found in your input array.");
        } else {
            System.out.println("Your number is not in the array.");
        }
        
        input.close(); // 关闭Scanner,释放资源
    }
}

关键说明

  1. 移除了多余的x变量,直接将输入值赋值给数组元素,简化代码结构。
  2. 新增布尔变量isFound记录查找状态,遍历数组时一旦找到匹配元素就标记为true并跳出循环,提升执行效率。
  3. 查找时从数组第一个有效索引开始遍历,避免越界问题。
  4. 最后关闭Scanner对象,养成良好的资源管理习惯。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 09:51:56