有没有人能帮我重写这个代码,用一个二维数组来循环并显示选择?
下面是一个问答类游戏。我有一个文本文件,其中包含程序读取的数据,因此首先是问题,然后是4个答案选项,然后是答案(文件中有20个问题):
1) What is 1+2 = ...?
a) 2
b) 3
c) 0
d) 1
b
...
代码如下:
import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class GameQuiz
{
public static void main(String[] args) {
String[] data = new String[120];
String question = "";
int count = 0;
try{
Scanner inFile = new Scanner(new File("questions.txt"));
while (inFile.hasNext()){
data[count] = inFile.nextLine();
count++;
}
inFile.close();
}catch(Exception e){
e.printStackTrace();
}
int choice = 0, numCorrect = 0, i = 0;
char correctAnswer = ' ', correct = ' ';
String answer= "";
String answerChoices[] = {"a", "b", "c", "d"};
for (int j = 0; j < 20; j++)
{
answer = "";
for (i = 0; i < 5; i++)
{
answer += data[i+(j*6)] + "\n";
}
correctAnswer = data[i+(j*6)].charAt(0);
choice = JOptionPane.showOptionDialog(null, answer, "Quiz Game",
0, 3, null, answerChoices, null);
if (choice == 0) correct = 'a';
if (choice == 1) correct = 'b';
if (choice == 2) correct = 'c';
if (choice == 3) correct = 'd';
if (correct == correctAnswer)
{
numCorrect ++;
JOptionPane.showMessageDialog(null, "Correct!");
}
else JOptionPane.showMessageDialog(null, "Sorry.\n"+
"The correct answer was "+correctAnswer);
}
JOptionPane.showMessageDialog(null, "You have "+numCorrect+"/20 correct answers.");
}
}
1条答案
按热度按时间2fjabf4q1#
你不需要改变太多:
以及:
它应该很好用。但是,您应该考虑更好的解决方案,如评论中所建议的。这不是最有效的方法。
编辑:您还需要更改数据[]声明: