Java数组查找元素后求和与平均值代码未执行问题求助
问题分析与修复
你的代码无法执行到求和逻辑,核心是语法错误导致编译失败,另外还有几处逻辑问题,逐一说明:
1. 致命语法错误(直接阻断程序运行)
搜索循环里的count_index++语句末尾缺少分号,Java要求每条语句必须以分号结尾,这个错误会触发编译报错,程序根本运行不到后面的求和代码。
修复:给count_index++补上分号:
if(inputted_array[i] == search) { System.out.println("Element " + search + " is found in index " + i + '.'); count_index++; // 补充分号 }
2. 数组长度与输入数量不匹配的逻辑问题
你让用户输入了数组元素数量The_scan,但实际创建的数组是固定长度5,且输入元素的循环也固定跑5次。如果用户输入的The_scan不是5,会出现:
- 若
The_scan大于5:搜索循环会超出数组范围,触发数组越界异常 - 若
The_scan小于5:搜索只检查前The_scan个元素,后面的元素不会被检索
修复:根据用户输入的The_scan动态创建数组并控制输入循环:
// 按输入的元素数量创建数组 int[] inputted_array = new int[The_scan]; // 输入循环次数改为The_scan for (int i = 0 ; i < The_scan; i++){ inputted_array[i] = sc.nextInt(); }
3. 求和循环的输出冗余问题
你把求和结果的打印放在了循环内部,这样每次累加都会打印一次中间值,体验不佳,建议移到循环外部只打印最终总和:
for (int i =0; i <inputted_array.length ;i++ ){ sum = sum + inputted_array[i]; } // 循环结束后打印最终总和 System.out.println("The sum value of the elements is:" + sum);
4. 平均值计算的整数除法问题
sum和inputted_array.length都是int类型,直接做除法会执行整数除法(舍去小数部分),即使赋值给float类型也无法保留小数精度。比如sum=10、length=3时,结果会是3.0而非3.333...
修复:将其中一个操作数转为float,触发浮点除法:
average = (float)sum / inputted_array.length;
修复后的完整代码
import java.util.Scanner; import java.util.Arrays; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter the number of element in the array:"); int The_scan = sc.nextInt(); int count_index,sum; count_index = 0; sum = 0; float average = 0; // 动态创建数组 int[] inputted_array = new int[The_scan]; for (int i = 0 ; i < The_scan; i++){ inputted_array[i] = sc.nextInt(); } System.out.println("The elements are: "+ Arrays.toString(inputted_array)); System.out.print("What is the element to be search: "); int search = sc.nextInt(); for(int i = 0; i < The_scan; i++ ){ if(inputted_array[i] == search) { System.out.println("Element " + search + " is found in index " + i + '.'); count_index++; } } if(count_index == 0){ System.out.println("Element "+search+" not found"); } // 求和循环 for (int i =0; i <inputted_array.length ;i++ ){ sum = sum + inputted_array[i]; } System.out.println("The sum value of the elements is:" + sum); // 浮点除法计算平均值 average = (float)sum / inputted_array.length; System.out.println("The average value of the elements is:" + average); } }
内容的提问来源于stack exchange,提问作者nights
相关产品推荐
相关产品推荐

