Reputation: 1620
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 );
}
}
Upvotes: 1
Views: 2064
Reputation: 153
First of all remove the latest if
if( userAnswer != answer )
{
feedback = "That is incorrect.";
}
and edit it to
do
{
String feedback ;
/*
your program here
*/
System.out.println("again 'Y'") ;
choice= scan.nextLine() ;
}while("Y".equalsIgnoreCase(choice))
Upvotes: 2