import java.util.Scanner;
import java.util.Random;
public class ResponseTimeProject
{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random rand = new Random();
System.out.print("Please enter your full name: ");
String name = in.nextLine();
System.out.println("Hello " + name + ". Please answer as fast as you can." + "\n\nHit <ENTER> when ready for the question.");
in.nextLine();
for (int count = 0; count < 4; count ++) {
String alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int character=(int)(Math.random()*26);
String s = alphabet.substring(character, character+1);
Random r = new Random();
int i;
for (i = 0; i < 1; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
long startTime = System.currentTimeMillis();
System.out.print("What is the next letter in the alphabet?" + " ");
String response = in.nextLine();
long endTime = System.currentTimeMillis();
String outcome;
if (alphabet.substring(character+1, character+2).equals(response)) {
outcome = "Correct!";
} else {
outcome = "Incorrect.";
}
long reactionTime = endTime - startTime;
System.out.println(outcome);
System.out.println("The average time it took you was " + reactionTime + " milliseconds");
System.out.println("Thank you " + name + ", goodbye.");
}
}
}
HELP: 此代码运行但它给了我错误的答案。我不知道出了什么问题。它打印不正确的结果。不知道我需要修复什么
答案 0 :(得分:0)
有问题的代码实际上是一团糟(从字符串中获取字符的子字符串,单个迭代的循环等)。但与此问题相关的基本问题是字母表中的下一个字母&#34;取决于打印但从未存储的输出。目前正在
for (i = 0; i < 1; i++) {
System.out.println(alphabet.charAt(r.nextInt(alphabet.length())));
}
因此从未保存过,所以没有什么比较它。
所以,保存下一个字符,然后打印出来。
char nextLetter = alphabet.charAt(r.nextInt(alphabet.length());
然后在比较中,对于响应,检查对实际值的响应,而不是字母表String中的一些随机子串。
response = in.nextLine();
char chkChar = response.charAt(0);
if (chkChar == nextLetter) {
...
}