[英]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.