Java Class!

  • Thread starter chroot
  • Start date
  • #126
I'm learning Java bymyself using The complete reference of java 2, fifth edition, Herbert Schildt..

I don't use sun's SDK, instead i'm using eclipse..

I was trying to make a small array thingy and here's the code

public class twod {
public static void main(String args[]) {
int twod [][] = new int [4][5];
int i, j, k = 0;

for (i=0; i < 4; i++)
for (j=0; j < 5; j++) {
twod[j]= k;
k++;

}
for (i=0; i < 4; i++){
for (j=0; j < 5; j++);

System.out.print( twod [j] + " "); System.out.println();

}

}


}



And here's the error...
Exception in thread "main"java.lang.ArrayIndexOutOfBoundsException:5
at arrays.twod.main(twod.java:29)

Which is in bold above...It seems to me that the code is correct, i still don't understand what's wrong with the print code..
 
  • #127
chroot
Staff Emeritus
Science Advisor
Gold Member
10,239
39
Nomy,

The line "for (j=0; j < 5; j++);", just above your System.out.println() call, is wrong. You should not have a semicolon there; instead, you should have an open brace. The semicolon indicates that the for loop is an empty loop, with nothing inside it.

The problem is that a for loop that increments j from 0 to less-than-5 will actually leave the value 5 in the j variable when it's done. The foor loops runs until the condition fails, and the variable j has to contain the value 5 for the condition to fail.

The System.out.println() call is being made -after- the for loop, since the loop is empty. At that point, j contains 5, and you're accessing the array outside its bounds.

- Warren
 
  • #128
Thanks a lot Chroot, now i understand...
 
  • #129
96
0
Your algorithm looks like what you did try to implement than it inadvertently turns out to be like that...:biggrin:

Chroot :wink:, I guess nomy wanted to print out the matrix with a semi-colon unfortunately appeared after the second for-loop as an apparent failure for the program to compile, and an exception is thrown right then to indicate the mistake.
 
  • #130
1
0
help!!!

hi, do u have any idea how i can cover the entire screen including the taskbar with an image as soon as a client starts, till a password is provided by the server??? The client should not be able to see anything, not even the taskbar till the administrator provides the right password. This has to be done in java... and soon... can u help???
 

Related Threads on Java Class!

  • Last Post
Replies
3
Views
1K
  • Last Post
Replies
4
Views
3K
  • Last Post
Replies
4
Views
2K
  • Last Post
Replies
4
Views
3K
  • Last Post
Replies
22
Views
4K
  • Last Post
Replies
11
Views
9K
  • Last Post
Replies
6
Views
1K
  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
13
Views
6K
  • Last Post
2
Replies
45
Views
16K
Top