java - 如何根据用户输入声明变量?
问题描述
我正在尝试创建一个程序来拼写检查用户输入的内容。他们必须正确输入 10 次“类型”这个词,它会显示一条消息,说明花了多长时间。
我的问题是结局永远不会到来,它不断要求您输入“类型”。我相信这是因为' 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");
}
}
解决方案
在 下System.out.println("Correct");
,您需要增加attempts
变量,否则它将保持为 0。
if(attempt.equals("type")) {
System.out.println("Correct");
attempts++; // <-- here
}
推荐阅读
- css - 如何在组件外调用现有的 onclick 函数?
- mysql - 选择 SQL 以获取差异
- electron - 电子屏蔽文件:// urls
- python - 为什么如果a = =(“B”或“C”)在a==“C”时即使我使用括号也不生效?
- angularjs - 'Mat-icon' 不是已知元素,验证它是否是该模块的一部分?
- c# - 我可以在 DevExpress DataGridView 中的查找和显示 expr 之间设置不同的值吗?
- discord.js - message.awaitReactions 没有检测到我的反应
- youtube-dl - 巨大的播放列表,youtube-dl 不会下载所有视频
- javascript - 第一个函数在空时更快,但当两者都被填充时,第一个函数更慢
- mysql - MySQL 自动增量不是从 1 开始