0

I am given the array measurements[]. I am supposed to write a for loop that goes through all the numbers and each time a number maximum is reached, the variable maximum is replaced. In the code I have so far, the output is saying that it cannot find the symbol i, but I thought that was the symbol I am supposed to use within a for-loop. Here is my code:

    double maximum = measurements[0];
    for (i = 0; i < measurements.length; i++) {
        if (array[i] > largest) {
            largest = array[i];
    }
    }
System.out.println(maximum);
Kalana
  • 5,631
  • 7
  • 30
  • 51
  • 1
    You need to declare i first. ''for (int i=0;...'' – marcelovca90 Feb 03 '20 at 04:11
  • See this answer [FInd Array Max Value](https://stackoverflow.com/a/18828505) Here you will find your desire answer. – Nayan Sarder Feb 03 '20 at 04:21
  • Agree with Beluga. Also, not sure why you're referencing "largest". Should that be "maximum"? – ELinda Feb 03 '20 at 04:30
  • `measurements` not defined, `i` not defined, `array` not defined, `largest` not defined, `maximum` not defined. We don't know that all variables `int` type or `double` type. And also you trying to get `largest` and output `maximum`. Op didn't ask for alternative answers but with his details we cannot provide exact answer for his question. This question has full of opinion based answers. – Kalana Feb 03 '20 at 04:47
  • If you dont want to use stream api then sort the array in ascending order and then get the array.size()-1 th element. – Vishwa Ratna Feb 03 '20 at 04:57

3 Answers3

1

You can also do this using Java stream api :

double maximum = Arrays.stream(measurements).max();
System.out.println(maximum);

Or a more concise code:

double maximum = Double.MIN_VALUE;
for(double measurement : measurements) {
    maximum = Math.max(maximum, measurement);
}
System.out.println(maximum);

Or, sort the array and return the last one

Arrays.sort(measurements);
System.out.println(measurements[measurements.length-1]);
royalghost
  • 2,773
  • 5
  • 23
  • 29
0

you can try this -

class MaxNumber
{
    public static void main(String args[])
    {
        int[] a = new int[] { 10, 3, 50, 14, 7, 90};
        int max = a[0];
        for(int i = 1; i < a.length;i++)
        {
            if(a[i] > max)
            {
                max = a[i];
            }
        }

        System.out.println("Given Array is:");
        for(int i = 0; i < a.length;i++)
        {
            System.out.println(a[i]);
        }

        System.out.println("Max Number is:" + max);
    }
}
Dipankar Baghel
  • 1,932
  • 2
  • 12
  • 24
0

You have not declared i inside the for loop or before the for loop.

double maximum = measurements[0];
    for (int i = 0; i < measurements.length; i++) {  //You can declare i here.
        if (array[i] > largest) {
            largest = array[i];
    }
    }
System.out.println(maximum);

You can also declare i before the for loop also

Dheeraj Joshi
  • 1,522
  • 14
  • 23