猿问

如何修复我的java代码,不工作

接受整数并将它们存储在数组中并输出其中最大数的程序。但以下代码不起作用


导入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);

}

}


长风秋雁
浏览 82回答 1
1回答

POPMUISE

您不需要再次循环数组来查找最大值。通过获取输入本身,我们可以通过与每个输入进行比较来获得最大数量。public static void main(String[] args){&nbsp; &nbsp; System.out.print("input the array'size : ");&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; int size = sc.nextInt();&nbsp; &nbsp; int arr[]=new int[size];&nbsp; &nbsp; System.out.println("input the array'value :");&nbsp; &nbsp; int max = 0;&nbsp; &nbsp; for(int i=0; i<size; i++){&nbsp; &nbsp; &nbsp; int var = sc.nextInt();&nbsp; &nbsp; &nbsp; arr[i] = var;&nbsp;&nbsp; &nbsp; &nbsp; if(var > max) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = var;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print("Input Array: "+Arrays.toString(arr));&nbsp; &nbsp; System.out.println("The largest number in array :"+ max);&nbsp;}
随时随地看视频慕课网APP

相关分类

Java
我要回答