簡體   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