Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I could not run the code please help me the err is Exception in thread \"main\"

ID: 3590409 • Letter: I

Question

I could not run the code please help me

the err is

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3

at sss2.sillyMatch(sss2.java:9)

at sss2.main(sss2.java:31)

the code is

public class sss2 {

static int sillyMatch(int A[], int B[], int num) { // 1

int sum = 900; // 3

int ctr = 0; // 4

while (ctr < num && A[ctr] < 555) { // 5

int ctr2 = 1; // 7

while (ctr2 < num && B[ctr2] < 555) { // 8

if (A[ctr] == B[ctr2]) { // 10

sum = sum + 11 + A[ctr]; // 11

}

ctr2 = ctr2 + 1; // 12

}

ctr = ctr + 1; // 14

}

return sum; // 16

}

public static void main(String args[]) {

int[] A = new int[3];

int[] B = new int[3];

A[0] = 1;

A[1] = 2;

A[2] = 3;

B[0] = 2;

B[1] = 3;

B[2] = 4;

System.out.println("sum = " + sillyMatch(A, B, 4));

}

}

Explanation / Answer

Error in code is: the code try to access the value from the array which is out of the boundary

(array limit is 0 to 3, accessing 4th index value will proceeds to error)

public class sss2 {

static int sillyMatch(int A[], int B[], int num) { // 1
int sum = 900; // 3
int ctr = 0; // 4
while (ctr < num-1 && A[ctr] < 555) { // 5
int ctr2 = 1; // 7
while (ctr2 < num-1 && B[ctr2] < 555) { // 8
if (A[ctr] == B[ctr2]) { // 10
sum = sum + 11 + A[ctr]; // 11
}
ctr2 = ctr2 + 1; // 12
}
ctr = ctr + 1; // 14
}
return sum; // 16
}

public static void main(String args[]) {

int[] A = new int[3];
int[] B = new int[3];
A[0] = 1;
A[1] = 2;
A[2] = 3;
B[0] = 2;
B[1] = 3;
B[2] = 4;

System.out.println("sum = " + sillyMatch(A, B, 4));

}
}
Sample run:
sum = 914
BUILD SUCCESSFUL (total time: 0 seconds)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote