Java 百分比始终等于0
我有这个方法。它基本上使用弹出窗口来显示简单的添加问题:Java 百分比始终等于0,java,Java,我有这个方法。它基本上使用弹出窗口来显示简单的添加问题: public static void addition () { JFrame frame = new JFrame(""); JOptionPane.showMessageDialog(frame, "++ You chose Addition! ++"); double percentage; String rank = ""; int i = 0; int x = 0; i
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);
}
}
假设我不断变得完美,然后在交互窗格上显示时百分比=100.0。然而,当我把1问题弄错时,我会自动得到一个零,而不是一个百分比数字(例如,我从3个问题中得到2个,
percentage=0
,而不是percentage=66.6
。我在声明它时试图去掉0,但它只会给我“变量可能尚未初始化”.将括号内的一个整数操作数强制转换为double
,以使用浮点运算
double percentage = ((double)x - y) / i * 100;
所有操作数(x、y、i和文字100)都是整数,因此使用整数算术除法,它将删除小数点后的所有内容。欢迎使用整数算术 尝试
percentage=((双)x-y)/i*100;
从:
乘法表达式的类型是它的提升类型
操作数。如果升级的类型为int或long,则使用整数算术 执行。
如果升级的类型为float或double,则 执行浮点运算
整数除法的问题是Java会截断小数部分。您可以生成
x
和y
浮点变量,也可以将它们转换为浮点变量进行除法,然后将它们转换回整数作为最终结果。使用双精度,开始时使用“整数算术”在JLS?@ingyhere中准确定义(见15.17.2)