Reputation: 35
public static void main(String[] args) {
int [] array= {4,5,7,1,5,4};
for(int j=0;j<array.length;j++) {
int min;
min=array[0];
if(array[j]>min) {
min=array[j];
}
}
System.out.print(min);
}
}
can you help me why min cannot be found?
Upvotes: 0
Views: 145
Reputation: 27792
You need to declare min
outside of the loop (because of scope):
int [] array= {4,5,7,1,5,4};
int min = array[0];// initialize min outside the loop.
for(int j=0;j<array.length;j++) {
//min=array[0]; If you leave this here, you will 'reset' min each time
if(array[j] < min) { // use "<" so that min will be the minimum
min=array[j];
}
}
System.out.print(min);
Also, you should not have min=array[0];
in your loop; this wil cause min
to "reset" back to array[0]
at each loop iteration. Instead, initialize it outside the loop. Finally, it looks like your code will set min
to the largest element in array
. To fix, reverse the comparision in the if statement.
Upvotes: 2
Reputation: 79921
You are attempting to access min
from a different scope from where it was declared.
You are declaring it inside your for
-loop:
for(int j=0; j < array.length; j++) {
int min;
min=array[0];
if(array[j]>min) {
min=array[j];
}
} // min can't be used after this.
However, you are using it outside of the loop. int min
is only valid within the scope of the for
loop block (the }
that closes the loop ends the block that min
is accessible in).
Move the min
declaration outside of the loop and it should work.
int min = array[0];
for (int i : array) {
if (i > min) {
min = i;
}
}
System.out.println("The min is: " + min);
I made your code a little more syntactically sweet with Java's for
-each loop.
Also, is there a logic error in your code? You call the variable min
but you are assigning numbers larger than min
to min. Sounds like you're looking for max value, not minimum?
Upvotes: 4
Reputation: 2717
Just moving min
out of the for loop doesn't help. It will overwrite min
everytime. Also move min=array[0];
out of the for loop.
Upvotes: 0
Reputation: 8724
Min is local to the for loop
int [] array= {4,5,7,1,5,4};
int min = array[0];
for(int j=0;j<array.length;j++) {
if(array[j]>min) {
min=array[j];
}
}
System.out.print(min);
Upvotes: 1
Reputation: 1980
Because the scope of the min variable lasts inside of the for block.
Upvotes: 0
Reputation: 41281
min
was declared inside the for loop.
Remove int min;
and put the following outside the for loop:
int min=0;
Since it's a local variable it must be initialized.
Also move min=array[0];
outside the for loop as well.
Upvotes: 0
Reputation: 2647
Min is being declared within the for-loop. If you move the declaration outside, it should work fine.
For example:
public static void main(String[] args) {
int [] array= {4,5,7,1,5,4};
int min=array[0];
for(int j=0;j<array.length;j++) {
if(array[j]>min) {
min=array[j];
}
}
System.out.print(min);
}
}
Upvotes: 1