Java - 如何循环测验直到用户决定退出?

时间:2016-09-04 18:43:09

标签: java while-loop prompt

我有以下简单的Java程序,它会提示用户进行减法测验。有人可以在正确的道路上推动我如何实现一个循环,该循环不断生成数字,进行计算,提示用户,并提供反馈,直到用户选择停止?我想它会涉及一个while循环,但用户如何表示他们想停止?我知道我可以告诉他们每当你想退出时按___,但程序的其余部分会不断提示用户输入一个整数...所以如果他们选择输入一个键怎么办?退出(假设" Q")当给他们下一个问题并且计算机正在等待整数的命令行响应时(因为Q不是整数)?

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 );


    }


}

1 个答案:

答案 0 :(得分:1)

首先删除最新的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))