import javax.swing.JOptionPane;
public class SubtrationQuizLoop {
public static void main(String[] args) {
final int NUMBER_OF_QUESTIONS = 5; //出5个减法题
int correctCount = 0;
int count = 0;
long startTime = System.currentTimeMillis(); //计时器
String output = " ";
while(count < NUMBER_OF_QUESTIONS) { //随机出题
int number1 = (int)(Math.random()*10);
int number2 = (int)(Math.random()*10);
if(number1 < number2) {
int temp=number1;
number1 = number2;
number2 = temp;
}
String answerString =JOptionPane.showInputDialog("What is "+number1+ " - "+number2+" ? ");
int answer = Integer.parseInt(answerString); //将字符串answerString转化为整型变量answer
if(number1 - number2 == answer) {
JOptionPane.showMessageDialog(null,"You are correct");
correctCount++;
}
else
JOptionPane.showMessageDialog(null,number1 +" - "+number2+" should be" + (number1-number2)," You are wrong! ",
JOptionPane.INFORMATION_MESSAGE);
count++;
output += "\n" +number1 +" - "+ number2 +" = " +answer +((number1 - number2 == answer) ? "correct" : "wrong"); //做结果总览输出
}
long endTime = System.currentTimeMillis();
long testTime = endTime-startTime;
JOptionPane.showMessageDialog(null,"Correct count is " + correctCount +"\n Test time is "+testTime/1000 +"seconds\n"+output);
}
}
特意写了JOptionPane的 对话框形式,觉得非常的合适。注意JOptionPane有两种输入方式,以JOptionPane.showMessageDialog为例,一种是JOptionPane.showMessageDialog(null,x)
另一种是JOptionPane.showMessageDialog(null,x,y,JOptionPane.INFORMATION_MASSAGE).上面的代码用到了两种写法,请自行观察输出的对话框有什么不同。