Home > Software design >  Complete the code to return the greatest value
Complete the code to return the greatest value

Time:12-04

I have an problem to undestand this question for the college. I just want to return the greastest value of this array but I don't undestand how I can do this. If someone explain to me how I solve this question, I really would appreciate.

public class Question1 {

    public static void main(String[] args) {

        double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};

        // code insert here

        System.out.println(bigger);

    }

}

I try to instance the object, but I was not successful.

public class Question1 {

     public static void main(String[] args) {

        double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};
        double bigger = Useful.bigger(list);

        bigger = list;
        list = new bigger();

        System.out.println(bigger);

    }

}

CodePudding user response:

It looks like you're trying to find the largest value in the array list, but your code is not doing that correctly. Here's one way you could do it:

  1. Create a variable bigger that starts with the first value in the array list.
  2. Loop through the rest of the values in the array, comparing each value to the current value of bigger.
  3. If a value is larger than the current value of bigger, update bigger to have that value.
  4. After the loop, bigger will have the largest value in the array.

Here's what that code might look like:

public class Question1 {
    public static void main(String[] args) {
        double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};

        // Step 1: initialize bigger with the first value in the array
        double bigger = list[0];

        // Step 2-3: loop through the rest of the values in the array,
        // comparing each value to bigger and updating bigger if necessary
        for (int i = 1; i < list.length; i  ) {
            if (list[i] > bigger) {
                bigger = list[i];
            }
        }

        // Step 4: print out the largest value
        System.out.println(bigger);
    }
}

You can also use the Math.max method to simplify the code a bit:

public class Question1 {
    public static void main(String[] args) {
        double[] list = {23.5, 65.9, 74.8, 65.3, 11.98, 76.44, 65.87};

        // Step 1: initialize bigger with the first value in the array
        double bigger = list[0];

        // Step 2-3: loop through the rest of the values in the array,
        // using Math.max to compare each value to bigger and update bigger if necessary
        for (int i = 1; i < list.length; i  ) {
            bigger = Math.max(bigger, list[i]);
        }

        // Step 4: print out the largest value
        System.out.println(bigger);
    }
}

I hope that helps! Let me know if you have any other questions.

  • Related