簡體   English   中英

java 中的隨機問題使用數組

[英]Random Questions in java using array

隨機問題Java

在下面的程序中,什么

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];
}

如何添加最高分和最低分?

這看起來像是一道家庭作業題,因此 StackOverflow 上的任何人都不太可能給您答案。 但是,我們可以帶您去做!

在此處查看next()返回的內容。 charAt(i)返回String中索引i處的字符。 | 運算符執行按位包含或運算。 還有- 97 ,我希望我不必告訴你什么是數學。

但是,考慮一下97代表什么。 請參閱ASCII 表

這是怎么回事。

  • 小寫字符 (az) 被 ASCII 編碼為十進制值 97 到 122
  • 大寫字符 (AZ) 被 ASCII 編碼為十進制值 65 到 90

請注意,它們的差異是 32。通過將第一個字符與 32(例如charAt(0) | 32 )進行 OR 運算,可以確保在輸入字母時將值轉換為小寫。 然后通過減去97得到一個從0 to 32的值。 然后該值用於索引到數組中。 不幸的是,如果有人輸入非字母,結果值可能會超過數組的大小或變為負數,從而導致拋出異常。

有更好的方法可以做到這一點。 並且應該驗證用戶輸入而不是盲目地接受它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM