odd thing happening in loop

  • From: Alex Hall <mehgcap@xxxxxxxxx>
  • To: programmingblind <programmingblind@xxxxxxxxxxxxx>
  • Date: Thu, 29 Oct 2009 19:46:31 -0400

Hi all,
The below is a java loop, simplified from a larger program I am
writing. When I look at it, I think that the loop will run from 0-3,
or four times, like saying
for(idx=0;idx<a.length;idx++)
Yet, when I run the program, I get my entire array printed, plus an
exception that I am trying to access a[4], which is of course out of
the array bounds. I cannot figure out how that loop can possibly go
over 4, though!! I very clearly state that if idx is greater than or
equal to a.length, break the loop, yet it still hits 4? It has to be
something simple in how Java works, but I have stared at this for over
an hour and cannot come up with anything. Changing around the order of
the statements does not help, either. In fact, the if...else was not
there before, I just added that and the break to see if it would help,
but it did not. If you see something wrong, please let me know!!

import java.util.*;
import java.io.*;
public class test{
public static void main(String[] args){

String[] a=new String[4];
String b="my,name,is,alex";
a=b.split(",");
int idx=0;

while(a[idx]!=null){
if(idx>=a.length){ //idx is out of bounds, so quit loop
break;
}//if
else{
System.out.println(a[idx]);
}//else
idx++;
}//while
}//main
}//test class

-- 
Have a great day,
Alex
My email is now: mehgcap@xxxxxxxxx
__________
View the list's information and change your settings at 
//www.freelists.org/list/programmingblind

Other related posts: