繁体   English   中英

如何修复此数组超出范围的异常

[英]How to fix this array out of bounds exception

我的任务是创建2个char数组,一个具有测试的“正确答案”,另一个具有用户输入的答案。 代码可以正常工作并正确编译,但是当我将所有10个答案输入程序后,我就会得到数组超出范围的异常。

这是代码片段:

    //Part 2
    char[] correctAnswers = {'b', 'd', 'a', 'a', 'c', 'a', 'b', 'a', 'c', 'd'}; //Char arrays
    char[] studentAnswers = new char[10];

    System.out.println("What are the students 10 answers?"); //Getting student answers
    for(int i = 0; i < correctAnswers.length; i++)
    {
        System.out.println("What is the answer to the " + i + " question");
        studentAnswers = scan.next().toCharArray();
    }

    int points = 0; //Used to calculate pass or fail


    for(int i = 0; i < correctAnswers.length; i++)
    {
        if (correctAnswers[i] == studentAnswers[i])
        points++;
    }




    if (points >= 8)
    {
        System.out.println("Congratulations! \nYou have passed exam.");
        System.out.println("Total number of correct answers: " + points); //print points
        System.out.println("Total number of incorrect answers: " + (correctAnswers.length - points)); //10 - points would equal the remaining amount of points available which would be how many were missed.
    }

    else
    {
        System.out.println("Sorry, you have not passed the exam!");
        System.out.println("Total number of correct answers: " + points);
        System.out.println("Total number of incorrect answers: " + (correctAnswers.length - points));
    }

问题是, studentAnswers = scan.next().toCharArray(); 在这里,您必须确保从用户那里得到10个字符长的响应。

为了做到这一点,你可以做这样的事情。

while(true){
    char[] temp=scan.next().toCharArray();
    if(temp.length==10){
        studentAnswers=temp;
        break;
    }
    else{
         //print that the length is incorrect.
    }
}

这样,您可以确保用户输入的字符序列长度为10。

您正在循环获得答案,这意味着您希望在每次迭代中得到一个答案,但是您要在每次迭代中分配整个studentAnswers数组。

你可能应该改变

studentAnswers = scan.next().toCharArray();

studentAnswers[i] = scan.nextLine().charAt(0);

假设您期望在每个输入行中有一个char答案。

如果输入以单行提供,并用空格分隔,则可以使用

studentAnswers[i] = scan.next().charAt(0);

或者您可以将整个循环替换为:

studentAnswers = scan.nextLine().split(" ");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM