loop / equals ==的问题

时间:2011-10-11 00:42:48

标签: java

我有以下一些代码,我遇到了一些困难。我对输出的期望应该是申请人#及其相关测试分数。两个数组的第一个位置是答案键。不太确定我在哪里出错了,但任何帮助都会受到赞赏。

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','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

输出结果为:

--------------------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)

3 个答案:

答案 0 :(得分:3)

不想为你解决问题因为它是作业,但这里有一个提示。

数组索引从0到元素数-1。检查你的循环以确保它没有超过结束。

答案 1 :(得分:2)

我还没有验证这是 问题,但它是一个红旗:

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

你的意思是?

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

每行只有10个。但i最多可达14个左右。因此j将超出范围。

答案 2 :(得分:2)

而不是

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

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

因为数组的长度始终相同。