简体   繁体   中英

How to fix this array out of bounds exception

I was tasked with creating 2 char arrays, one with the "correct answers" for a test and another with the user input answers. The code works and compiles correctly however when I get all 10 answers input into the program, I get an array out of bounds exception.

Here is the code snippet:

    //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));
    }

The problem is, studentAnswers = scan.next().toCharArray(); in here you have to make sure that you are getting exactly 10 character long response from the user.

In order to do that, you can do something like this.

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

This way you can make sure that the user enters exactly an character sequence of length 10.

You are getting the answers in a loop, which means you are expecting one answer in each iteration, but you are assigning the entire studentAnswers array in each iteration.

You probably should change

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

to

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

assuming you expect a single char answer in each input line.

If the input is supplied in a single line, separated by spaces, you can use

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

or you can replace the entire loop with :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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