Not Greater Than Problem

I’m making a few random classes that do various things at the moment but I’m slightly stuck on this method. Every time I run the below program it works perfectly except it throws an array index out of bounds exception before it finishes; I know the cause of the problem but the only way I can think of fixing it would be to find some way to have an ‘is not greater than’ operator to make sure that z never goes past the end of the char array.

If anyone can figure out a fix to this it would help. Maybe I’ll get lucky and figure it out myself soon. =)

class MessageDisplay
{
	public MessageDisplay()
	{
	}
	
	public static void typeWriterDisplay(String x)
	{
		char[] array = x.toCharArray();
		int i = 0;
		int z = 0;
		while( i <= x.length() )
		{
			System.out.println( array[z] );
			z++;
		}
	}
	
	public static void main(String args[])
	{
		typeWriterDisplay("Lololol");
	}
}

instead of [icode]i <= x.length()[/icode] use [icode]i < x.length();[/icode]…

But this is strange code anyways ^^

Better use this code:

[icode]
public static void typeWriterDisplay(String str) {
for (int i = 0; i < str.length(), i++) {
System.out.println(str.charAt(i));
}
}
[/icode]

Ah, I figured I could use either a for or while loop but I guess the for loop is better. It’s all working now, thanks!

Now to add a thread to finish the effect!

You’re not incrementing i, you’re incrementing z. You also need to exlude x.length();


		while( z < x.length() )
		{
			System.out.println( array[z] );
			z++;
		}

Rule of thumb: almost always use for-loops

every loop can do everything, use “for” most of times

Can’t remember the last time I used while…oh yeah, Java4K.

Yeah, it’s not the most used loop ever… I usually just use it for ‘while(variable= true)’.

I see what you did there.

O.o So did I thanks to you, lol…