I have this method. It basically uses popup windows to display simple addition questions:
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);
}
}
Say I keep getting perfect, Then percentage = 100.0
when displayed on the interactions pane. HOWEVER when I get one question wrong, instead of getting a percentage number, i automatically get a zero (ex say I got 2 out of 3, percentage = 0
instead of percentage = 66.6
. I tried getting rid of the 0 when declaring it, but it only gives me "variable may not have been initialized".