Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why XX and not X??????

 
Carol Murphy
village idiot
Bartender
Posts: 1202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Okay you gurus of java, I can't figure out what the difference is between these two programs. One compiles and runs just fine, the other doesn't. The difference is in the flip() method. One explicitly goes through the array, the other tries to use a for loop to do the same, but it doesn't work. Why won't the for loop work?
class XX
{
public static void main( String[] args )
{
boolean[] b = new boolean[ 4 ] ;
b[ 0 ] = false ;
b[ 1 ] = true ;
b[ 2 ] = false ;
b[ 3 ] = true ;

System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;

flip( b ) ;
System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;
}
static void flip( boolean[] b )
{
System.out.print("b is "+ b.length +" items long. \n" );
b[ 0 ] = !b[ 0 ] ;
b[ 1 ] = !b[ 1 ] ;
b[ 2 ] = !b[ 2 ] ;
b[ 3 ] = !b[ 3 ] ;
}
}
class X
{
public static void main( String[] args )
{
boolean[] b = new boolean[ 4 ] ;
b[ 0 ] = false ;
b[ 1 ] = true ;
b[ 2 ] = false ;
b[ 3 ] = true ;

System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;

flip( b ) ;
System.out.println( b[ 0 ] ) ;
System.out.println( b[ 1 ] ) ;
System.out.println( b[ 2 ] ) ;
System.out.println( b[ 3 ] ) ;
}
static void flip( boolean[] b )
{
System.out.print("b is "+ b.length +" items long. \n" );
for( int x = 0; x<=b.length; x++)
{
b[ x ] = !b[ x ] ;
}
}
}
 
chi Lin
Ranch Hand
Posts: 348
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice the "=" in x<=b.length, this is where the ArrayIndexOutOfBoundException come.

static void flip( boolean[] b )
{
System.out.print("b is "+ b.length +" items long. \n" );
for( int x = 0; x<=b.length; x++)
{
b[ x ] = !b[ x ] ;
}
}
}
[ November 01, 2003: Message edited by: chi Lin ]
 
Doug Dunn
Author
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The standard idiom for looping through an array is as follows.

Do you see the difference? In this case, the length of the array is four, but the highest index value is three.
 
Carol Murphy
village idiot
Bartender
Posts: 1202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Doh!!!
What the heck was I thinking?
Oh, wait, I wasn't thinking!
Thanks for pointing that out to me!!!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic