1,编写一个Java程序,接收一个整数数组作为输入,并打印数组中的最大值
时间: 2024-10-16 15:08:30 浏览: 59
当然可以。在Java中,你可以通过创建一个简单的主函数来实现这个功能。下面是一个示例:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// 创建一个Scanner对象获取用户输入
Scanner scanner = new Scanner(System.in);
// 提示用户输入整数数组长度
System.out.println("请输入整数数组的长度:");
int length = scanner.nextInt();
// 创建一个整数数组,并初始化为0
int[] array = new int[length];
// 提示用户逐个输入数组元素
System.out.println("请输入数组的元素(按顺序输入):");
for (int i = 0; i < length; i++) {
array[i] = scanner.nextInt();
}
// 找到并打印数组的最大值
int max = findMax(array);
System.out.println("数组中的最大值是: " + max);
// 关闭Scanner
scanner.close();
}
// 使用循环找到数组中的最大值
private static int findMax(int[] numbers) {
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
return max;
}
}
```
在这个程序中,我们首先读取用户输入的数组长度,然后遍历数组并记录每个元素。`findMax`方法会遍历整个数组,找出最大的那个值。最后,我们将结果打印出来。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)