vendredi 30 avril 2021

Display the correct input for the largest value in array [duplicate]

I already get the smallest number but for the largest it display the wrong number. How to get and display the correct number for the largest value?

public static void main(String[] args) { final int ARRAY_SIZE = 100;

    int[] array = new int[ARRAY_SIZE]; 

    int count = 0; // hold the number of elements in an array 
    int sum=0;
    int index;
    

    // everytime we add an element, the count is incremented. 
    
    Scanner uInput = new Scanner(System.in); 
    System.out.print("Enter a number or -1 to quit: "); 

    int number = uInput.nextInt(); 

    while (number != -1 && count < array.length) 

    { 

    array[count] = number; 

    count++; 

    System.out.print("Enter a number or -1 to quit: "); 

    number = uInput.nextInt(); 
    }
    
    //display all the valid elements in the array 

    for (index = 0; index < count; index++) 

    { 

    System.out.println("Element #"+ index+ ": "+ array[index]); 

    //Task #1: Tutorial 04 write your code here 

    sum += array[index];
    System.out.println(sum);
    }
    int average = sum/count;
    System.out.println("Average: " + average);
    
    int smallest = array[0], largest = array[0];
    for (int i : array) {
        if (array[i] < smallest) {
            smallest = array[i];
        }
        else if (array[i] > largest) {
            largest = array[i];
        }
            System.out.println("Smallest: " + smallest);
            System.out.println("Largest: " + largest);
            return;
    
    } 

   }
}

Output: Enter a number or -1 to quit: 2 Enter a number or -1 to quit: 4 Enter a number or -1 to quit: 6 Enter a number or -1 to quit: 8 Enter a number or -1 to quit: -1 Element #0: 2 2 Element #1: 4 6 Element #2: 6 12 Element #3: 8 20 Average: 5 Smallest: 2 Largest: 6 (The largest should be number "8")

Aucun commentaire:

Enregistrer un commentaire