接受整数并将它们存储在数组中并输出其中最大数的程序。但以下代码不起作用导入java.util.Scanner;公共类测试2 {public static void main(String[] args){ System.out.print("input the array'size : ");Scanner sc = new Scanner(System.in);int size = sc.nextInt();int arr[]=new int[size];System.out.print("input the array'value :");for(int i=0; i<size; i++){ int var = sc.nextInt(); arr[i] = var; }System.out.print("inputed value: ");for(int i=0; i<size; i++) {System.out.print(arr[i]+ " ");}int max = 0;for(int j=0; j<size; j++){ if(max<arr[j+1]){ max = arr[j]; } else { continue; }}System.out.println("the largest number in array :"+ max);}}
1 回答

POPMUISE
TA贡献1765条经验 获得超5个赞
您不需要再次循环数组来查找最大值。通过获取输入本身,我们可以通过与每个输入进行比较来获得最大数量。
public static void main(String[] args){
System.out.print("input the array'size : ");
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int arr[]=new int[size];
System.out.println("input the array'value :");
int max = 0;
for(int i=0; i<size; i++){
int var = sc.nextInt();
arr[i] = var;
if(var > max) {
max = var;
}
}
System.out.print("Input Array: "+Arrays.toString(arr));
System.out.println("The largest number in array :"+ max);
}
添加回答
举报
0/150
提交
取消