【发布时间】:2019-10-04 10:23:34
【问题描述】:
我正在尝试创建一个程序来对用户输入的内容进行拼写检查。他们必须正确输入 10 次“type”这个词,它会显示一条消息,说明花了多长时间。
我的问题是结局永远不会到来,它不断要求您输入“类型”。我相信这是因为'while (attempts < required)'。我想我需要做 required = 正确的尝试。 if attempt = type,那么它将产生 1 个正确的值。任何帮助表示赞赏。也很抱歉,我不知道如何构造问题
public static void printHeading(String heading) {
System.out.println(heading.toUpperCase());
for (int i = 0; i < heading.length(); i++)
System.out.print("=");
System.out.println();
System.out.println();
}
public static int runTutorial(Scanner in, String word, int required) {
Scanner sc = new Scanner(System.in);
String attempt = word;
int correct = 0;
int attempts = 0;
while (attempts<required)
{
System.out.print("Enter '" + word + "': ");
attempt = sc.nextLine();
if(attempt.equals("type")) {
System.out.println("Correct");
}
else {
System.out.println("Try again");
}
}
return attempts;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
final int TIMES = 10; //required number of correct repetitions
final String WORD = "type"; //the word to type
long startTime, endTime; //start and end time of typing test
double seconds; //elapsed time in seconds
int attempts;
printHeading("Typing Tutor");
System.out.println("You need to type a word " + TIMES +
" times correctly, as quickly as you can");
System.out.println("Your word today will be '" + WORD + "' (do not enter the quotes)");
System.out.println();
System.out.println("Type anything and press enter to begin");
//The test
System.out.println("Press enter to start the test");
sc.nextLine();
startTime = System.currentTimeMillis();
attempts = runTutorial(sc, WORD, TIMES);
endTime = System.currentTimeMillis();
//Test report
seconds = (double)(endTime - startTime) / 1000;
System.out.println("You took " + seconds + " seconds and " + attempts +
" attempts to correctly type '" + WORD + "' " + TIMES + " times");
System.out.println();
printHeading("Come back for more pracice soon");
}
}
【问题讨论】:
-
你忘了在你的
while循环中增加attempts,它的值总是0。 -
这与声明变量有什么关系?
-
@JohnSmith 你的问题不清楚。如果您希望我们帮助您,我建议您先学习基本术语。有声明一个变量,实例化一个变量,设置一个变量的值。不,它们不一样。必须先声明一个变量,然后才能梦想使用它,这是真的。但是你在标题中的问题是关于声明一个变量,你的解释是关于一些不同的东西
标签: java user-input variable-declaration