用JAVA定义一个int型的一维数组,数组长度从键盘输入,分别给元素赋值随机整数,赋值后请遍历数组,找出最大值位置和最大值
时间: 2024-05-27 21:11:30 浏览: 60
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入数组长度:");
int length = input.nextInt();
int[] array = new int[length];
Random random = new Random();
for (int i = 0; i < length; i++) {
array[i] = random.nextInt(100);
}
int max = array[0];
int index = 0;
for (int i = 0; i < length; i++) {
if (array[i] > max) {
max = array[i];
index = i;
}
}
System.out.print("数组元素为:");
for (int i = 0; i < length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
System.out.println("最大值位置为:" + index + ",最大值为:" + max);
}
}
阅读全文