Reputation: 991
I am writing a small program which uses a for loop.
1 Scanner sc = new Scanner(System.in);
2 int T = sc.nextInt();
3 for(int j = 1; j < 2T-1; j+=2){
4 doSomething();
5 }
However, this one gives me an error.
The error message says:
javac Main.java -g
Main.java:12: error: ';' expected
for(int j = 1; j < 2T-1; j+=2){
^
Main.java:12: error: not a statement
for(int j = 1; j < 2T-1; j+=2){
^
Main.java:12: error: ')' expected
for(int j = 1; j < 2T-1; j+=2){
^
Main.java:12: error: ';' expected
for(int j = 1; j < 2T-1; j+=2){
^
4 errors
I don't quite understand the 'statement' in an error message.
1) How come it produces errors?
2) What's the difference between statement and expression?
Upvotes: 0
Views: 36
Reputation: 201447
Java isn't an algebraic math system. This
for(int j = 1; j < 2T-1; j+=2){
should be
for(int j = 1; j < (2*T) - 1; j += 2){
2T-1
simply isn't a valid statement; variable names cannot start with a number, the compiler detects that 2
would be a valid statement and is communicating that. However, T-1
is then in an unexpected place.
Upvotes: 1
Reputation: 4609
You have to use
for(int j = 1; j < (2*T)-1; j+=2){
or
for(int j = 1; j < 2*T-1; j+=2){
Both will give you the same result.
Upvotes: 0