我即将发布的代码片段来自一个程序,该程序应该向用户询问一系列多项选择题。然后,程序将为每个问题保留分数,并且总计将存储在另一个数组中。我将有多个玩家玩这个,这就是为什么我需要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返回给另一个将它存储在数组中的方法。
答案 0 :(得分:2)
好的,所以看起来你需要在你的方法中传递当前用户的序数,这样它就可以在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
的内容,只能写入