数组中的 Java 最小值和最大值

2022-09-02 19:13:41

我的代码没有给出错误,但是它没有显示最小值和最大值。代码是:

Scanner input = new Scanner(System.in);

int array[] = new int[10];

System.out.println("Enter the numbers now.");

for (int i = 0; i < array.length; i++) {
    int next = input.nextInt();
    // sentineil that will stop loop when 999 is entered
    if (next == 999) {
        break;
    }
    array[i] = next;
    // get biggest number
    getMaxValue(array);
    // get smallest number
    getMinValue(array);
}

System.out.println("These are the numbers you have entered.");
printArray(array);


// getting the maximum value
public static int getMaxValue(int[] array) {
    int maxValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] > maxValue) {
            maxValue = array[i];
        }
    }
    return maxValue;
}

// getting the miniumum value
public static int getMinValue(int[] array) {
    int minValue = array[0];
    for (int i = 1; i < array.length; i++) {
        if (array[i] < minValue) {
            minValue = array[i];
        }
    }
    return minValue;
}

//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has  //been stored in an array!!!!!!!
public static void printArray(int arr[]) {
    int n = arr.length;

    for (int i = 0; i < n; i++) {
        System.out.print(arr[i] + " ");
    }
}

我是否需要 system.out.println() 来显示它,或者返回应该工作?


答案 1
getMaxValue(array);
// get smallest number
getMinValue(array);

您正在调用这些方法,但未使用返回的值。

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

答案 2

您也可以尝试此操作,如果您不想通过您的方法执行此操作。

    Arrays.sort(arr);
    System.out.println("Min value "+arr[0]);
    System.out.println("Max value "+arr[arr.length-1]);