gpt4 book ai didi

java - 将数组元素相加并将它们存储到另一个数组中? ( java )

转载 作者:行者123 更新时间:2023-12-02 08:04:19 24 4
gpt4 key购买 nike

我即将发布的代码片段来自一个程序,该程序应该询问用户一系列多项选择问题。然后,程序将记录每个问题的分数,并将总分存储在另一个数组中。我将有多个玩家玩这个游戏,所以这就是为什么我需要 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。然后我想累积score[]的总和并将其存储在total[]的每个元素中。我将总计返回到另一个方法,该方法将其存储在数组中。

最佳答案

好吧,看来您需要在方法中传递当前用户的序号,以便它可以计算 total 数组中的正确位置。由于您似乎想要汇总多个问答 session 的总分,因此您需要从外部传递 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,只写入它。

关于java - 将数组元素相加并将它们存储到另一个数组中? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8406604/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com