Random Questions in Java
above the program below, what is "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?
CodePudding user response:
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.
CodePudding user response:
Here is what is going on.
- lower case characters (a-z) are ASCII encoded as decimal values 97 thru 122
- upper case characters (A-Z) are ASCII encoded as decimal values 65 thru 90
Notice that their difference is 32. By ORing the first character with 32 (e.g. 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.