Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A Simple Control Flow Question

 
zan hsieh
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I merge some code in Thinking in Java as below:
//: c03:ListCharacters.java
// Demonstrates "for" loop by listing
// all the ASCII characters.
///:~
The book states the syntax for for-loop:
for(initialization; Boolean-expression; step)
statement
Is anything wrong in my code?
Thanks.

[This message has been edited by Marilyn deQueiroz (edited August 14, 2001).]
 
Marilyn de Queiroz
Sheriff
Posts: 9063
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Notice how in the section you commented out, you declare your variables on two separate lines. Why? Because they are different types.

Also, notice how you declared
<pre> int i , j ; </pre>
after
<pre> char c ; </pre>
If you wrote this line this way
<pre> int i , int j ; </pre>
it would not compile.

Likewise, if you declare variables in the initialization section of a for loop, they must all be the same type.

So if you change
<pre>char c = 0, int i = 0, int j = 1 ; </pre>
to
<pre>int c = 0, i = 0, j = 1 ; </pre>
this problem will be resolved.

[This message has been edited by Marilyn deQueiroz (edited August 14, 2001).]
 
zan hsieh
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I actually intend to ask it is possible to initialize more than one primitive types in the first argument of for-loop. If you could, please write an example.
Thanks.
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can initialize more than one variable, but they need to be of the same type (you can only pick ONE type).
The clue that Marilyn was trying to give you is that the semi-colon is required to end one primitive type declaration, before beginning another.
char c ; //notice the semi-colon
int i, j; // two of the same followed by a semi-colon
In the init portion of the for loop you only get ONE semi-colon, then you are in the next portion of the statement. Therefore only ONE primitive type declaration.
 
zan hsieh
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic