簡體   English   中英

添加數組元素的總和並將它們存儲到另一個數組中? (JAVA)

[英]Adding the sum of array elements and storing them into another array? (Java)

我即將發布的代碼片段來自一個程序,該程序應該向用戶詢問一系列多項選擇題。 然后,程序將為每個問題保留分數,並且總計將存儲在另一個數組中。 我將有多個玩家玩這個,所以這就是為什么我需要2個陣列。

這是我有的:

//Asks questions and stores score in array
public static int [] questions ()
{
    userinput=""; //input will be stored in here
    int total[]= new int[100];
    int score[]=new int[5];
    for(int i=0; i < ps.length; i++)
    {
        userinput=JOptionPane.showInputDialog(que[i]); //Outputs a question stored in   another array in another method.
        if (response.equals(ans[i])) //this compares the user input to the correct answer of the question, which is in another method.
        {
            JOptionPane.showMessageDialog(null,"You selected " + " " + ans[i] + " You were correct, 1 point!");
            score[i]=1;
            total[i]=total[i]+score[i];
        }
        else if(!response.equals(ans[i])) // If the answer isn't correct
        {
            score[i]=0; // I want to assign 0 for the question
            JOptionPane.showMessageDialog(null,"You're wrong!, The correct answer was "+ans[i]);
        }
    } // close loop
    return total; // return's this to another method which will do all of the other work
}

我好像遇到了這個問題:

JOptionPane.showMessageDialog(null,"You selected " + " " + ans[i] + " You were correct, 1 point!");
score[i]=1;
total[i]=total[i]+score[i];    

如果答案是正確的,我想在score []中為每個元素添加1。 然后我想累積得分[]的總和並將其存儲在total []的每個元素中。 我將total返回到另一個將其存儲在數組中的方法。

好的,所以你似乎需要在你的方法中傳遞當前用戶的序數,這樣它才能計算出total組中的正確位置。 由於您似乎希望在多個問題/答案會話中匯總總分,因此您需要從外部傳遞total

public static void questions(int userOrdinal, int[] total) {
    final int questionsPerUser = 5;

    userinput = ""; //input will be stored in here
    for (int i = 0; i < questionsPerUser; i++) {
        userinput = JOptionPane.showInputDialog(que[i]); //Outputs a question stored in   another array in another method.
        if (response.equals(ans[i])) //this compares the user input to the correct answer of the question, which is in another method.
        {
            JOptionPane.showMessageDialog(null, "You selected " + " " + ans[i] + " You were correct, 1 point!");
            total[userOrdinal * questionsPerUser + i] = 1;
        } else if (!response.equals(ans[i])) // If the answer isn't correct
        {
            total[userOrdinal * questionsPerUser + i] = 0;
            JOptionPane.showMessageDialog(null, "You're wrong!, The correct answer was " + ans[i]);
        }
    } // close loop
}

對不起,我仍然無法理解為什么你需要score數組,因為你的初始代碼與total[i]++ ,你從不讀取score內容,只寫入它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM