File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes A Simple Control Flow Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "A Simple Control Flow Question" Watch "A Simple Control Flow Question" New topic
Author

A Simple Control Flow Question

zan hsieh
Greenhorn

Joined: Aug 13, 2001
Posts: 3
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

Joined: Jul 22, 2000
Posts: 9044
    
  10

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).]


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
zan hsieh
Greenhorn

Joined: Aug 13, 2001
Posts: 3
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

Joined: Sep 29, 2000
Posts: 8521
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.

"JavaRanch, where the deer and the Certified play" - David O'Meara
zan hsieh
Greenhorn

Joined: Aug 13, 2001
Posts: 3
Thanks.
 
 
subject: A Simple Control Flow Question
 
Similar Threads
Question from jqplus
Issue with reversing a string
value of i?
I am not getting the required output...
ASCII - UNICODE