我试图用不同的算术运算符显示不同的表达式,例如 2 + 6 = , 7-1 = , 9 * 2 = , 10/5 = 。从我目前的代码中只有"/"
运算符的整数正在运行,其他运算符不会。我的代码是:
fnum0 = (int) ((double) ((Math.random() * 10)));
snum0 = (int) ((double) ((Math.random() * 10)));
display.setText(fnum0+"+"+ snum0+"= ");
fnum1 = (int) ((double) ((Math.random() * 10)));
snum1 = (int) ((double) ((Math.random() * 10)));
display.setText(fnum1+"-"+ snum1+"= ");
fnum2 = (int) ((double) ((Math.random() * 10)));
snum2= (int) ((double) ((Math.random() * 10)));
display.setText(fnum2+"*"+ snum2+"= ");
fnum3= (int) ((double) ((Math.random() * 10)));
snum3= (int) ((double) ((Math.random() * 10)));
display.setText(fnum3+"/"+ snum3+"= ");
答案 0 :(得分:1)
问题是您正在设置文本4次,有效地覆盖每个后续调用的文本。
如果你想要文本中的所有4个表达式,你必须连接所有字符串,如下所示:
display.setText(fname0 + "+" + snum0+"=\n"+fname1 + "-" + snum1+"=\n"+fname2 + "*" + snum2+"=\n"+fname3 + "/" + snum3+"=\n");
我还建议您通过创建字符串并附加它来使其更具可读性。
String str = fname0 + "+" + snum0+"=\n";
str += fname1 + "-" + snum1+"=\n";
str += fname2 + "*" + snum2+"=\n";
str += fname3 + "/" + snum3+"=\n";
display.setText(str);
要进行随机操作,请尝试此操作。
fnum0 = (int) ((double) ((Math.random() * 10)));
snum0 = (int) ((double) ((Math.random() * 10)));
String str = "";
int operation = (int) ((double) ((Math.random() * 4)));
if(operation == 0)
str = fnum0 + "+" + snum0;
else if(operation == 1)
str = fnum0 + "-" + snum0;
else if(operation == 2)
str = fnum0 + "*" + snum0;
else
str = fnum0 + "/" + snum0;
display.setText(str);
基本上,这会生成一个0到3的随机数,并使用它来确定显示哪个操作
答案 1 :(得分:1)
它只显示'/'操作(最后一个),因为每次调用setText()
时都会覆盖前一个操作字符串。您需要使用最终形成的字符串调用该方法。因此,您可以使用append()
函数来连接字符串并在显示视图中全部表示它们。
尝试以下方法:
StringBuilder str = new StringBuilder(1000);
fnum0 = (int) ((double) ((Math.random() * 10)));
snum0 = (int) ((double) ((Math.random() * 10)));
str.append(fnum0+" + "+ snum0+"= \n");
fnum0 = (int) ((double) ((Math.random() * 10)));
snum0 = (int) ((double) ((Math.random() * 10)));
str.append(fnum0+" - "+ snum0+"= \n");
fnum0 = (int) ((double) ((Math.random() * 10)));
snum0 = (int) ((double) ((Math.random() * 10)));
str.append(fnum0+" * "+ snum0+"= \n");
fnum0 = (int) ((double) ((Math.random() * 10)));
snum0 = (int) ((double) ((Math.random() * 10)));
str.append(fnum0+" / "+ snum0+"= \n");
display.setText(str);