开发者

Problems with loop / equals ==

I have the following bit of code that I am having some difficulty with. My expectation for output should be the applicant # with their correlated test score. The first position of both arrays is for the answer key. Not quite sure where I am going wrong with this, but any help would be appreciated.

public class applicantCheck
{
//* main method
public static void main(String[] args)
{
int i = 0, j = 0, correct;
//* initialization of applicant id's and answers
int[] appID = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14};
char[][] appAnswers = { {'N','Y','N','N','Y','N','N','Y','N','Y'},
{'N','Y','Y','N','Y','N','Y','Y','N','Y'},
{'N','Y','N','Y','N','Y','Y','Y','N','N'},
{'N','Y','Y','N','Y','Y','Y','Y','Y','Y'},
{'Y','Y','N','N','Y','N','N','Y','Y','Y'},
{'Y','Y','N','Y','Y','Y','N','N','T','N'},
{'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'},
{'N','Y','N','N','N','Y','N','Y','N','Y'},
{'Y','N','Y','N','Y','N','Y','N','Y','N'},
{'Y','Y','Y','N','N','Y','Y','N','Y','N'},
{'N'开发者_C百科,'N','N','N','N','N','N','N','N','N'},
{'Y','N','Y','Y','N','Y','Y','N','Y','N'},
{'N','Y','N','N','Y','Y','N','N','N','Y'},
{'N','Y','N','Y','N','Y','N','Y','N','Y'},
{'Y','N','Y','N','Y','Y','N','Y','N','Y'} };
System.out.println("Applicant #\t\tMark (out of " + appAnswers[i].length + ")");
for (i = 1; i < appID.length; i++)
{
    System.out.printf("%-9d", appID[i]);
    correct = 0;
    for (j = 0; j <= i; j++)
    {
        if (appAnswers[0][j] == appAnswers[i][j])
        {
            correct++;
        }
    }
    System.out.printf("%10d\n", correct);
} // end of for loop
System.out.println();
} // end of main
} // end of file

The output is:

--------------------Configuration: <Default>--------------------
Applicant #     Mark (out of 10)
1                 2
2                 3
3                 3
4                 4
5                 3
6                 2
7                 6
8                 3
9                 2
10       Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 10
    at applicantCheck.main(applicantCheck.java:36)


Don't want to solve the problem for you since it is homework, but here's a hint.

Array indexes go from 0 to the number of elements -1. Check your loop to make sure it doesn't go past the end.


I haven't verified if this is the problem, but it's a red-flag:

for (j = 0; j <= i; j++)

Did you mean this?

for (j = 0; j < 10; j++)

You only have 10 in each row. But i goes up to 14 or so. Therefore j will go out of bounds.


Instead of

for (j = 0; j <= i; j++)

try

for (j = 0; j < 10; j++)

since the array is always the same length.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜