我有这个方法。它基本上使用弹出窗口来显示简单的加法问题:
public static void addition ()
{
JFrame frame = new JFrame("");
JOptionPane.showMessageDialog(frame, "++ You chose Addition! ++");
double percentage;
String rank = "";
int i = 0;
int x = 0;
int y = 0;
while (true){
int add1 = (int)(Math.random()*9) + 1;
int add2 = (int)(Math.random()*9) + 1;
i = i + 1;
int addtotal = add1 + add2;
try{
String test = JOptionPane.showInputDialog(frame, i + "). What's " + add1 + " + " + add2 + "?");
if (test == null){
choose();
}
int convertToNum = Integer.parseInt (test);
if (convertToNum == addtotal){ // if the user got it right
x++;
final ImageIcon icon = new ImageIcon(new URL("http://cdn2.iconfinder.com/data/icons/basicset/tick_64.png")); //Custom Icon for the JFrame below, The image destination uses a URL link to show the icon
JOptionPane.showMessageDialog(null, "Nice Job!\nYou Currently Got " + x + " Out of " + i + " Correct!",":D",JOptionPane.INFORMATION_MESSAGE,icon);
}
else { // if the user got it wrong
JOptionPane.showMessageDialog(frame, "Sorry, but that was wrong.\n" + add1 + " + " + add2 + " = " + addtotal + " . \n You Currently Got " + x + " Out of " + i + " Correct!","Whoops",JOptionPane.INFORMATION_MESSAGE);
y++;
}
}
catch (Exception e){
JOptionPane.showMessageDialog(frame, "I Didn't Understand That.","...",JOptionPane.ERROR_MESSAGE);
y++;
}
System.out.println ("x: " +x);
System.out.println ("i: " +i);
percentage = (x - y) / i * 100;
System.out.println ("% :" + percentage);
}
}
假设我不断完善,然后percentage = 100.0
在交互窗格中显示。但是,当我做错一个问题时,我没有得到一个百分比数字,而是自动得到一个零(例如,我在 3 个中得到了 2 个,percentage = 0
而不是percentage = 66.6
。我在声明它时尝试摆脱 0,但它只给了我“变量可能尚未初始化”。