• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with for loops

 
nitya satheesh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey!
I have a problem with the for loops in the following program.It's a little silly but it's really bugging me..

class twoDArray{
public static void main(String args[]){
int twoD[]=new int[4][5];
int i,j,k=0;
for(i=0;i<4;i++)//why no curly braces here
for(j=0;j<5;j++){
twoD[i][j]=k;
k++;
}
for(i=0;i<4;i++){
for(j=0;j<5;j++)
system.out.println(twoD[i][j]+" ");
system.out.println();
}
}
}

why doesn't the first for loop need any curly braces?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not just for loops. While loops are the same way.

According to the JLS, you can have exactly one 'thing' in the body of your loop. that thing can be (for example) a for-loop. Or an executable statement. Or a block of code surrounded by curly braces.

So, your first loop has one thing in it - a for-loop.

Now...just because you CAN leave those braces off doesn't mean you SHOULD. Pretty much everyone here is going to tell you to ALWAYS use them, whether they are strictly needed or not.
 
Jj Hill
Ranch Hand
Posts: 41
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
System should be capitalized..
 
Campbell Ritchie
Sheriff
Pie
Posts: 49813
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch
You ought to indent that code, then you would be able to see the relationships between the different parts. You should also tell us (for both your questions) where the question comes from.
 
Manu Somasekhar
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not a good practice to avoid braces like that.
 
nitya satheesh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot!!!
I have one more question about this code.
The output of this code is supposed to be :
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

but I get
0
1
2
3
4

5
6
7
8
9......

Why this difference?

I got this code form a book called Complete reference :Java.
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
you have to fiddle with System.out.print and System.out.println in some *rare* case nowadays...


 
Manu Somasekhar
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi nitya ,
what about changing



to



 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic