3

I know this is stupid, but it is sort of hard to research properly due to it's simple nature, I suppose.

for (char letter = 'a', int num = 1; maxLine - num > 0; letter++, num++) {
    System.out.print(letter);
}

This is a standard way to define variables inside a for condition for C and C#, but it doesn't seem to work here. Why?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alex
  • 715
  • 1
  • 8
  • 29
  • can u ever define `int i =0 ,char c ='a';`?, don't think it works in c++ or c# – Ramanlfc Mar 16 '16 at 15:11
  • Please don't add meta-tags like "" to titles. The correct way is to accept an answer, or - if the question hadn't been closed - posting your own answer (if none of the current answers suffice) and accepting it after the cooldown period. – Mark Rotteveel Mar 17 '16 at 12:39
  • This question was wrongly closed. Its not a duplicate(or at least the duplicate cross is wrong coz that question refers to c++ not java). – theprogrammer Jul 03 '20 at 03:31

2 Answers2

1

Because the variable declaration in a for loop follows that of local variable declaration.

Similar to how the following is not valid as a local declaration because it contains multiple types:

char letter = 'a', int num = 1;

It is also not valid in a for loop. You can, however, define multiple variables of the same type:

for (int n = 0, m = 5; n*m < 400; n++) {}

As to why the designers made it that way, ask them if you see them.

Community
  • 1
  • 1
Darth Android
  • 3,437
  • 18
  • 19
0

This does not work in C/C++ either, not sure about C#, though.

The first part of your for statement might have multiple variables, but with the same type. The reason for this is that it is generally not possible to write:

int n = 0, char c = 5;

If you would like to do this, you needed two statements. Similarly, the first part of for only accepts one statement, so that you cannot put two ones in here.

IceFire
  • 4,016
  • 2
  • 31
  • 51