Java:如何在用户需要时使用标记值退出程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28016252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 12:50:07  来源:igfitidea点击:

Java: How to use a sentinel value to quit a program when the user wants

java

提问by JcireR

The only thing i am missing is to use a sentinel value, like zero, to quit the loop when the user wants, even without enter any gussing.

我唯一缺少的是使用一个哨兵值,如零,在用户需要时退出循环,即使没有输入任何 gussing。

import java.util.Scanner;
import java.util.Random;

public class RandomGuessing {

    //-----------------------------------------------------------------------------------------------
    //This application prompt to the user to guess a number. The user can still playing until
    //guess the number or want to quit
    //-----------------------------------------------------------------------------------------------

    public static void main(String[] args) {

        Scanner scan = new Scanner (System.in);
        Random rand = new Random();

        int randNum = rand.nextInt(100) + 1;
        System.out.println(randNum);

        System.out.println("\t\tHi-Lo Game with Numbers\t\t\n\t   Guess a number between 1 and 100!!!\n");

        String ans;
        int attemptsCount = 0;

        do {

            System.out.print("Guess the number: ");
            int input = scan.nextInt();

            while(input != randNum){

                attemptsCount++;

                if(input < randNum){
                    System.out.println();
                    System.out.print("low guessing\nEnter new number: ");
                    input = scan.nextInt();
                }
                else{
                    System.out.println();
                    System.out.print("high guessing\nEnter new number: ");
                    input = scan.nextInt();
                }
            }

            System.out.println();
            System.out.println("Congrats!!! You guess right\nAttempts: "+attemptsCount);

            System.out.println();
            System.out.print("You want to play again (yes/no): ");
            ans = scan.next();

            randNum = rand.nextInt(100) + 1; //generate new random number between same above range, 
                                             //if the user wants to keep playing.

        }while (ans.equalsIgnoreCase("yes"));


    }
}

回答by Bohemian

Here's a simple approach:

这是一个简单的方法:

// inside do loop
System.out.print("Guess the number (-1 to quit): ");
int input = scan.nextInt();
if (input == -1) {
    break;
}

回答by roeygol

Try using this code for exiting totaly:

尝试使用此代码退出 totaly:

System.exit(0);