and1can
and1can

Reputation: 79

java changing value in for loop

I tested my algorithm in python and it does exactly what I want it to do. Now I just want to write the same code in java. I am running into two issues. One with line 7 and one with line 8. I would like to know why i is not detected even though I have int i inside the for loop. I am taking Java next semester, so sorry if this is a really easy bug to deal with.

 public class HelloWorld{

 public static void main(String []args){
    int[] a = {1, 0, 12, 11};
    int max = a[0];
    for (int i:a); {
        if (max <  i); {
            max =  i;
        }
    }
System.out.print("max"); // if method is void, then cannot return value   
    }
 }

Upvotes: 1

Views: 120

Answers (2)

ThisClark
ThisClark

Reputation: 14823

This is how I would write your code to make it work. As others have pointed out, be careful with where you put your semi colons.

int[] a = { 1, 0, 12, 11 };
int max = a[0];
for (int i : a) {
    if (i > max) {
        max = i;
    }
}
System.out.print(max);

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

Remove the trailing semi-colons from the for and if statements which are terminating those statements

Upvotes: 8

Related Questions