【发布时间】:2019-05-12 17:40:18
【问题描述】:
这是我根据运动创建的一个测验,它会询问用户每次尝试 3 次的一系列问题。从那里它汇总每个玩家的分数并以二维数组的形式显示它,它比较分数并打印最高分数。我将如何使用冒泡排序(不是 array.sort)按第二个索引(分数)对二维数组(记分牌)进行排序。
import java.util.*;
class miniproj
{
public static void main(String[] args)
{
Questions[] questions = setQuestions(); // store array of questions using setquestions method
askQuestion(questions); // run method askquestion using questions parameter (array)
}
public static Questions[] setQuestions()
{
Questions[] questions = new Questions[4]; //create array of type questions
Questions A = new Questions(); // create new questons type called A
A.question = "What team won the world cup in 1966?";
A.options = " A. Germany\n B. France\n C. England\n D. Wales";
A.answer = "C";
questions[0] = A; // the first question in the aray is A
Questions B = new Questions();
B.question = "Who are the current EPL title holders?";
B.options = " A. Arsenal\n B. Bournemouth\n C. Chelsea\n D. Manchester City";
B.answer = "D";
questions[1] = B;
Questions C = new Questions();
C.question = "Who is the current Golden Boot holder 2017/18 season?";
C.options = " A. Lionel Messi\n B. Harry Kane\n C. Cristiano Ronaldo\n D. Davidson Sanchez";
C.answer = "A";
questions[2] = C;
Questions D = new Questions();
D.question = "Which team has most goals";
D.options = " A. Arsenal\n B. Bournemouth\n C. Chelsea\n D. Manchester City";
D.answer = "A";
questions[3] = D;
return questions; // return array of questions
}
public static void askQuestion(Questions[] array)
{
int correct = 0;
Scanner sc = new Scanner(System.in);
String[][] scoreboard = new String[4][2];
for(int m = 0; m < scoreboard.length; m++) {
correct = 0;
System.out.println("What is your name");
scoreboard[m][0] = sc.nextLine();
for(int i = 0; i < 4; i ++) // this loops for all four questions
{
for(int k = 4; k > 1; k --)
{
System.out.println(array[i].question);
System.out.println(array[i].options);
String answer = sc.nextLine();
if(answer.equalsIgnoreCase(array[i].answer)) // this loops til correct answer is given
{
System.out.println("Correct");
correct = correct + 1;
break;
}
else
{
System.out.println("Incorrect, you have " + (k - 2) + " tries left");
}
}
}
scoreboard[m][1] = Integer.toString(correct);
System.out.println(correct + " questions correct");
}
int mostCorrectIndex = 0;
for (int c = 1; c < scoreboard.length; c++) {
if (Integer.parseInt(scoreboard[c][1]) > Integer.parseInt(scoreboard[mostCorrectIndex][1]))
mostCorrectIndex = c;
}
System.out.println("The person with the highest score is " + scoreboard[mostCorrectIndex][0]);
for (int b = 0; b < scoreboard.length; b++) {
System.out.println(Arrays.toString(scoreboard[b]));
}
}
}
class Questions
{
String question;
String options;
String answer;
}
【问题讨论】:
-
我不明白
String[][] scoreboard代表什么。这个数组中有哪些值,它们是什么意思? -
用户名在索引 0 上。他们获得的分数在索引 1 上。
标签: java arrays sorting multidimensional-array bubble-sort