Java Minimum and Maximum values in Array

前端 未结 13 930
没有蜡笔的小新
没有蜡笔的小新 2020-12-01 06:32

My code does not give errors, however it is not displaying the minimum and maximum values. The code is:

Scanner input = new Scanner(System.in);

int array[]          


        
13条回答
  •  离开以前
    2020-12-01 07:22

    I have updated your same code please compare code with your's original code :

    public class Help {
    
    public static void main(String args[]){
        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;
        }
    
        System.out.println("These are the numbers you have entered.");
        printArray(array);
    
        // get biggest number
        System.out.println("Maximum: "+getMaxValue(array));
        // get smallest number
        System.out.println("Minimum: "+getMinValue(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] + " ");
        }
    }
    }
    

提交回复
热议问题