java - 使用 JOptionPane.showMessageDialog 告诉用户他们有多少正确和错误
问题描述
按照下面代码中的注释:添加另外 8 个问题和答案,最后告诉用户他们得到了多少正确和错误的分数。
import javax.swing.*;
public class Quiz
{
public static void main(String[] args)
{
String[] questions =
{"How many players on a basketball team?\nA. 5 B. 6 C. 7",
"How many points for a basket?\nA. 1 B. 2 C. 3",
"How many points for a free throw?\nA. 1 B. 2 C. 3"};
//Add 8 more questions and answers
char[] answers = {'A', 'B','A' };
char ans = ' ';
int x, correct = 0;
String entry;
boolean isGood;
for(x = 0; x < questions.length; ++x)
{
isGood = false;
int firstError = 0;
while(!isGood)
{
isGood = true;
entry = JOptionPane.showInputDialog
(null,questions[x]);
ans = entry.charAt(0);
if(ans != 'A' && ans != 'B' && ans != 'C')
{
isGood = false;
if(firstError == 0)
{
questions[x] = questions[x] +
"\nYour answer must be A, B or C.";
firstError = 1;
}
}
}
if(ans == answers[x])
{
++correct;
JOptionPane.showMessageDialog(null,
"Correct!");
}
else
JOptionPane.showMessageDialog(null, "The correct answer is " + answers[x]);
}
// Using JOptionPane.showMessageDialog tell the user how many they got right and wrong
}
}
解决方案
这是您的代码的更新版本:
import javax.swing.*;
public class Quiz
{
public static void main(String[] args)
{
String[] questions =
{"How many players on a basketball team?\nA. 5 B. 6 C. 7",
"How many points for a basket? \nA. 1 B. 2 C. 3",
"How many points for a free throw? \nA. 1 B. 2 C. 3",
"Question 4? \nA. 1 B. 2 C. 3",
"Question 5? \nA. 1 B. 2 C. 3",
"Question 6? \nA. 1 B. 2 C. 3",
"Question 7? \nA. 1 B. 2 C. 3",
"Question 8? \nA. 1 B. 2 C. 3",
"Question 9? \nA. 1 B. 2 C. 3",
"Question 10? \nA. 1 B. 2 C. 3",
"Question 11? \nA. 1 B. 2 C. 3"};
//Add 8 more questions and answers
char[] answers = {'A', 'B', 'A', 'C', 'C', 'A', 'B', 'A', 'A', 'C', 'B'};
char ans = ' ';
int x, correct = 0;
String entry;
boolean isGood;
for(x = 0; x < questions.length; ++x)
{
isGood = false;
int firstError = 0;
while(!isGood)
{
isGood = true;
entry = JOptionPane.showInputDialog (null,questions[x]);
ans = entry.charAt(0);
if(ans != 'A' && ans != 'B' && ans != 'C')
{
isGood = false;
if(firstError == 0)
{
questions[x] = questions[x] + "\nYour answer must be A, B or C.";
firstError = 1;
}
}
}
if(ans == answers[x])
{
++correct;
JOptionPane.showMessageDialog(null, "Correct!");
}
else
JOptionPane.showMessageDialog(null, "The correct answer is " + answers[x]);
}
JOptionPane.showMessageDialog(null, "You got " + correct + " correct answers and " + (answers.length-correct) + " wrong answers.");
}
}
您需要自己修改问题的文本:)。
推荐阅读
- javascript - 如何将自动完成建议限制为最多 10 个?
- javascript - css中所选开始日期和结束日期之间的悬停效果
- javascript - 保护 ASHX Web Handler 不被用户调用
- hibernate - JPA Persistence 上下文缓存始终为空并创建新的实例类导致内存泄漏
- macos - Visual Studio for Mac:连接到 TFS
- java - 方法 count 文件中的单词
- html - 制作正确的人字形字体的尖端 - 很棒的图标触摸 div 的结尾
- esp8266 - 写入 Sparkfun ESP8266 Thing 上的串行监视器
- javascript - 如何将此代码转换为 JAVASCRIPT 字符串并稍后对其进行评估?
- dockerfile - 带有 asp 核心控制台应用程序的 Linux Docker 容器