我试图让用户选择在他/她获得4个乘法问题后退出程序。如果他/她选择继续,我必须给他/她另一次机会退出每次。我希望这是有道理的..我发布的代码有效,但我觉得我必须改变一些东西才能让用户选择终止。
import java.security.SecureRandom; //program will use random numbers
import java.util.Scanner; //program will need user input
public class RandomMultiplication
{
public static void main(String[] args)
{
while(true)//continues to play game
{
question();
}
}
public static void question()
{
boolean repeat = false;
SecureRandom randomNumbers = new SecureRandom();
//pick random numbers (1-9) for multiplication scenario
int number1 = randomNumbers.nextInt(10); //first number
int number2 = randomNumbers.nextInt(10); //second number
while(!repeat)
{
int responseCode = randomNumbers.nextInt(4);
if(multiplicationProblem(number1,number2))
{
switch(responseCode)
{
case 0: System.out.println("Very Good!");
break;
case 1: System.out.println("Excellent!");
break;
case 2: System.out.println("Keep up the good work!");
break;
case 3: System.out.println("Nice work!");
break;
}//ends switch
repeat = true; //stops repeating the same question
}//end if statement
else
{
responseCode = randomNumbers.nextInt(4);
switch(responseCode)
{
case 0: System.out.println("No. Please try again!");
break;
case 1: System.out.println("Wrong, Try once more!");
break;
case 2: System.out.println("Don't give up!");
break;
case 3: System.out.println("No. Keep trying!");
break;
}//ends switch
}//ends else condition
}//ends while loop
}
public static boolean multiplicationProblem(int number1, int number2)
{
Scanner input = new Scanner(System.in);
int userInputAnswer;
int correctCounter = 0;
System.out.printf("How much is %d times %d?", number1, number2);
userInputAnswer = input.nextInt();
if (userInputAnswer == number1 * number2)
{
return true;
}
else
{
return false;
}
}
}