66 951
Assignments Done
99,1%
Successfully Done
In October 2018

Answer to Question #19861 in Java | JSP | JSF for nohra

Question #19861
62-9. You coded the following in file Test.java:
int [ ] [ ] a = { { 9, 8, 7, 6 },
{ 10, 20, 30, 40 } };
for ( int j = 0; j <= a[1].length; j++ )
{
if ( a[1][j] == 20 ) // line 14
{
System.out.println( "Found 20 at column index " + j
+ " of second row" );
}
}
The code compiles properly, but when you run, you get the following output:
Found 20 at column index 1 of second row
Exception in thread "main" java.lang.ArraylndexOutOfBoundsException:
at Test.main(Test.java:14)
Explain what the problem is and how to fix it.
Expert's answer
your condition is out of the loop is wrong.
your code: for (int j = 0; j <= a[1].length; j++) isnot correct
for(int j = 0; j < a[1].length; j++) iscorrect
index of array in java is counted from 0.
More information about the array by reference: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions