集册 Java实例教程 带有嵌套do ... while循环的猜谜游戏

带有嵌套do ... while循环的猜谜游戏

欢马劈雪     最近更新时间:2020-01-02 10:19:05

528
带有嵌套do ... while循环的猜谜游戏
/*from nowjava - 时代Java*/

import java.util.Scanner;


public class GuessingGame{

  static Scanner sc = new Scanner(System.in);

    public static void main(String[] args) {

    boolean keepPlaying = true;


    while (keepPlaying)

    {

      boolean validInput;

      int number, guess;

      String answer;


      number = (int)(Math.random() * 10) + 1;


      System.out.println("A number between 1 and 10.");

      System.out.print("Guess:");

      do

      {

        guess = sc.nextInt();

        validInput = true;

        if ( (guess < 1) || (guess > 10) )
        /*
        时代Java 提供
        */

        {

            System.out.print("between 1 and 10. Try again: ");

            validInput = false;

        }

      } while (!validInput);


      if (guess == number)

        System.out.println("right!");

      else

        System.out.println("Wrong: The number was " + number);


      do{

        System.out.print("\nPlay again? (Y or N)");

        answer = sc.next();

        validInput = true;

        if (answer.equalsIgnoreCase(
展开阅读全文