Reputation: 11
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);
Upvotes: 0
Views: 3200
Reputation: 2808
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]);
Upvotes: 1
Reputation: 1582
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
Upvotes: 0
Reputation: 2039
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);
}
}
Upvotes: 0