Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

the if loop

 
Chris Lenney
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have 2D array called grid which in column [0] has string in the format 01/03/2003, I don't want to deal with date formats as im only concentrated on the year, therefore i use substring and compare it to the year in question (as seen below).

My question is, how come the if statement only seems to iterate once? It should iterate a fair few times as the first 30 dates are "2003".

if (grid[row][0].substring(6,10).equals("2003")) {
out03.write(grid[row][1] + "\n");
System.out.println(row + "\n");
row ++;
}

Thanks, Chris
 
Kail Limas
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a loop surrounding the if statement right?

Without a loop like for or while the if statement is only used once.
 
Peter Chase
Ranch Hand
Posts: 1970
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you (original poster) were expecting your posted code to iterate through a loop, I am interested to know from which other programming language you have come to Java. Something rather different, I guess!
 
Chris Lenney
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
lol no, java is my first language, im just a bit slow. Thanks for your help, i'll put it inside another loop. Cheers
 
Francesco Bianchi
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two little hints:
1. About code readability and code reuse: use endsWith() instead of substring() followd by an equals()
2. About code reliability: what happens if for some reason you call the substring on a String which is long...let's say...4 chars?
 
fred rosenberger
lowercase baba
Bartender
Posts: 12180
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to be sure we are clear... there is no such thing as an "if loop". the if is a conditional. IF something is true, do what's in the block. it is designed to only fire once.

if you want a loop, you need a for, a for-each, a while, or a do-while loop.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic