我知道我之前只是问了一个问题facepalm
顺便说一句,这是在 Java 编码中。
在每个人都非常非常有用的建议之后(非常感谢你们)
我设法让超过一半的程序按照我想要的方式运行。
一切都指向数组中我希望它们去的地方。现在我只需要访问数组,以便它随机打印正确的信息。
这是我当前使用的代码:
给我问题的具体代码是这样的:
长aa; int abc;
for (int i = 0; i < x; i++)
{
aa = Math.round(Math.random()*10);
String str = Long.toString(aa);
abc = Integer.parseInt(str);
String[] userAnswer = new String[x];
if(abc > x)
{
JOptionPane.showMessageDialog(null,"Number is too high. \nNumber Generator will reset.");
break;
}
userAnswer[i] = JOptionPane.showInputDialog(null,"Question "+quesNum+"\n"+questions[abc]+"\n\nA: "+a[abc]+"\nB: "+b[abc]+"\nC: "+c[abc]+"\nD: "+d[abc]);
answer = userAnswer[i].compareTo(answers[i]);
if(answer == 0)
{
JOptionPane.showMessageDialog(null,"Correct. \nThe Correct Answer is "+answers[abc]+""+i);
}
else
{
JOptionPane.showMessageDialog(null,"Wrong. \n The Correct Answer is "+answers[abc]+""+i);
}//else
最佳答案
我不确定你的问题是什么,但我注意到了这一行:
aa = Math.round(Math.random()*10);
如果您需要一个介于 0
和 10
之间的随机 int
,最好使用:
java.util.Random.nextInt(int n)
: Returns a pseudorandom, uniformly distributedint
value between 0 (inclusive) and the specified value (exclusive)
您首先要在别处创建一个实例(您应该只需要在您的应用程序中执行一次):
Random r = new Random();
然后,每当您需要一个介于 0
和 10
之间的随机整数时,您可以:
aa = r.nextInt(10+1);
您可以只写 11
,但写 10+1
可能还有一个额外的好处,即提醒读者这是一个半开范围。
好的,我刚刚注意到以下几点:
aa = Math.round(Math.random()*10);
String str = Long.toString(aa);
abc = Integer.parseInt(str);
这没什么意义。你应该能够做到:
aa = r.nextInt(10+1);
abc = (int) aa;
虽然坦率地说,我不确定您是否真的首先需要这么多变量。也许你可以写:
int aa = r.nextInt(10+1);
您还应该考虑使用 String.format
而不是进行所有这些连接。
System.out.println(
String.format("%d + %d = %s", 3, 4, 7)
); // prints "3 + 4 = 7"
API 链接
关于java - 数组计数不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2960578/