Java——如何循环测验直到用户决定退出? [英] Java -- how to loop a quiz until the user decides to quit?
问题描述
我有以下简单的 Java 程序,它提示用户进行减法测验.有人可以在我如何实现一个循环的正确路径上轻推我,该循环可以不断生成数字、进行计算、提示用户并提供反馈,直到用户选择停止?我想它会涉及一个 while 循环,但是用户如何发出他们想要停止的信号?我知道我可以告诉他们每当您想退出时按 ___",但程序的其余部分不断提示用户输入一个整数......那么如果他们选择输入一个键退出(假设"Q") 什么时候给他们下一个问题并且计算机正在等待一个整数的命令行响应(因为 Q 不是整数)?
I have the following simple Java program that prompts a user with a subtraction quiz. Can someone nudge me along in the right path of how I can implement a loop that keeps generating numbers, doing the calculations, prompting the user, and giving feedback until the user chooses to stop? I imagine it would involve a while loop, but how would the user signal that they want to stop? I understand I could tell them to "press ___ whenever you want to quit", but the rest of the program is constantly prompting for the user to enter an integer...so what if they choose to enter a key to quit (suppose "Q") when the next question is given to them and the computer is waiting for a command-line response that is an integer (since Q is not an integer)?
import java.util.Random;
import java.util.Scanner;
public class MathQuiz
{
public static void main( String [] args )
{
// random number generator
Random rng = new Random();
// scanner to get user's answer
Scanner scan = new Scanner( System.in );
// generates random number, 1 <= n <= 9
int num1 = rng.nextInt( 10 );
int num2 = rng.nextInt( 10 );
// prompt, answer, user's answer, and feedback
String prompt = "What is " + num1 + " - " + num2 + "?";
int answer = Math.abs( num1 - num2 );
int userAnswer = 0;
String feedback = "That's correct, way to go!";
// figure out which is larger
if( num1 < num2 )
{
prompt= "What is " + num2 + " - " + num1 + "?";
}
System.out.println( prompt );
userAnswer = scan.nextInt();
if( userAnswer != answer )
{
feedback = "That is incorrect.";
}
System.out.println( feedback );
}
}
推荐答案
首先删除最新的if
if( userAnswer != answer )
{
feedback = "That is incorrect.";
}
并将其编辑为
do
{
String feedback ;
/*
your program here
*/
System.out.println("again 'Y'") ;
choice= scan.nextLine() ;
}while("Y".equalsIgnoreCase(choice))
这篇关于Java——如何循环测验直到用户决定退出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!