[英]Random Questions in java using array
在下面的程序中,什么
index = (new Scanner(System.in).next().charAt(0) | 32) - 97;
意思?
private static String showQNA(String quiz, String[] options) {
Random random = new Random();
final int max = options.length;
int[] randomselect = new int[max];
int index = 0;
for (int n = 0; n < max; n++) {
do {
index = random.nextInt(max);
} while (randomselect[index] != 0);
randomselect[index] = 1 + n;
}
System.out.printf(quiz);
for (int i = 0; i < max; i++) {
index = randomselect[i] - 1;
System.out.printf("%c. %s\n", 'A'+i , options[index]);
}
System.out.print("answer:");
index = (new Scanner(System.in).next().charAt(0) | 32) - 97;
return options[randomselect[index]-1];
}
如何添加最高分和最低分?
这是怎么回事。
请注意,它们的差异是 32。通过将第一个字符与 32(例如charAt(0) | 32
)进行 OR 运算,可以确保在输入字母时将值转换为小写。 然后通过减去97
得到一个从0 to 32
的值。 然后该值用于索引到数组中。 不幸的是,如果有人输入非字母,结果值可能会超过数组的大小或变为负数,从而导致抛出异常。
有更好的方法可以做到这一点。 并且应该验证用户输入而不是盲目地接受它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.