java在main()中,创建一个长度为5的整型数组,利用循环,对该数组进行控制台输入赋值,统计数组中所有非负数的平均值,分析可能出现的异常,并做处理(如果可以得到最终的平均值则显示出平均值,如果得不到,则给出相应提示)
时间: 2023-06-12 11:05:58 浏览: 68
以下是Java代码实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int[] arr = new int[5];
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
System.out.print("请输入第" + (i + 1) + "个数:");
try {
arr[i] = Integer.parseInt(scanner.nextLine());
} catch (NumberFormatException e) {
System.out.println("输入的不是整数!");
i--;
}
}
int sum = 0, count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 0) {
sum += arr[i];
count++;
}
}
try {
double avg = sum / (double) count;
System.out.println("所有非负数的平均值为:" + avg);
} catch (ArithmeticException e) {
System.out.println("数组中没有非负数!");
}
}
}
```
代码中,我们首先创建一个长度为5的整型数组,并利用循环对数组进行输入赋值。在输入过程中,如果用户输入的不是整数,则会捕获 `NumberFormatException` 异常,并提示用户重新输入。
接着,我们使用循环遍历整个数组,统计所有非负数的和以及数量。如果数组中没有非负数,则除法运算会发生 `ArithmeticException` 异常,我们在 `catch` 代码块中给出相应提示。如果可以得到最终的平均值,则将其输出到控制台上。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![-](https://img-home.csdnimg.cn/images/20241231044937.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)