File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes the if loop Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "the if loop" Watch "the if loop" New topic

the if loop

Chris Lenney

Joined: Mar 01, 2006
Posts: 5
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

Joined: Jul 09, 2007
Posts: 24
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

Joined: Oct 30, 2001
Posts: 1970
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!

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Chris Lenney

Joined: Mar 01, 2006
Posts: 5
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

Joined: Jun 22, 2007
Posts: 62
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?

SCJP 5 & 6, SCWCD 5, SCBCD 5
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11915

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.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: the if loop
It's not a secret anymore!