简体   繁体   中英

Random Questions in java using array

Random Questions in Java

In the program below, what does

index = (new Scanner(System.in).next().charAt(0) | 32) - 97;

mean?

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

How to add highest and lowest score?

This looks like a homework question, so it's unlikely that anyone on StackOverflow will give you the answer. But, we can lead you to it!

Check out what next() returns here . charAt(i) returns the character in a String at index i . The | operator performs a bitwise inclusive OR operation. And the - 97 , I hope I don't have to tell you what math is.

However, consider what 97 represents. See the ASCII table .

Here is what is going on.

  • lower case characters (az) are ASCII encoded as decimal values 97 thru 122
  • upper case characters (AZ) are ASCII encoded as decimal values 65 thru 90

Notice that their difference is 32. By ORing the first character with 32 (eg charAt(0) | 32 ), this ensures the value is converted to lower case if a letter was entered. Then by subtracting 97 one gets a value from 0 to 32 . That value is then used to index into an array. Unfortunately, if someone were to enter a non-letter, the resulting value could exceed the size of the array or become negative, resulting in an exception being thrown.

There are better ways of doing this. And one should validate user input rather than blindly accepting it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM