Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Q from John Hunt M.E

 
Vineet Sharma
Ranch Hand
Posts: 51
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
public class Calc{
public static void main(String args[]){

int total = 0;
for(int i =0, j = 10; total>30; ++i, --j){
System.out.println(" i = " + i + " : j = " + j);
total += (i + j);
}
System.out.println("Total " + total);
}
}
Answers:
A. Runtime Error
B. Compiletime Error
C. Prints out "Total = 0"

The correct answer is C. I also ran the prog. and the answer did come out to be C. However, I think it should be B for the following reasons:
1. Type of 'j' has not been declared.
2. In the first part of the for loop (int i = 0, j = 10)is incorrect.
Please Explain
Thanks
 
Carl Trusiak
Sheriff
Posts: 3340
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is an acceptable way(htough can lead to confusion) way to declare multiple variables. It can be done inside the declaration section of a for loop or any where you can declare variables
int i=0, j=5, k=3; //accptable
This brings to lightt another requirement, you can not mix declarations in the declaration of a for loop
//legal
for(int 1 = 0, j = 10;
or
int i = 0;
int j = 0;
for(i = 0, j = 10;
//illegal
int i = 0;
for(i = 0, int j =10;
or
int j = 0;
for(int i =0, j = 10;

Hope this helps
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic