首页 > 解决方案 > 我想不出使用 while 循环将 -1 实现为哨兵值。

问题描述

我不知道使用 while 循环将 -1 实现为哨兵值。请注意,程序需要一直运行,除非用户输入值 -1 它应该停止。从技术上讲,当用户输入标记值(-1)时,程序应该随时停止。

import java.util.Scanner;
import java.util.Random;
public class Multi {

        public static void main(String[] args) {

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

        int randomOne, randomTwo, product, userInput;

        while(true) {
        randomOne = Math.abs(rand.nextInt()%10);
        randomTwo = Math.abs(rand.nextInt()%10);

        product = randomOne * randomTwo;

        System.out.println("How much is " + randomOne + " times " + randomTwo 
        + "?");
        userInput = scan.nextInt();

        if (product == userInput) {
            System.out.println("Very Good!");
            }

        else {
        while (product != userInput) {
            System.out.println("No. Please try again.");
            System.out.println("How much is " + randomOne + " times " + 
         randomTwo + "?");
            userInput = scan.nextInt();

         if (product == userInput) {
                System.out.println("Very Good!");

        }
        }}


        }   
        }
        }

因此,当我们向用户询问输入时,如果他们输入 -1,程序应该停止。

标签: java

解决方案


您可以在每次迭代时检查该值是否为 -1,然后编写一个 break 语句,但下面是一个稍微干净的实现。

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

public class Multi {

  public static void main(String[] args) {

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

    int randomOne, randomTwo, product, userInput;
    boolean playingGame = true;

    while (playingGame) {
      randomOne = Math.abs(rand.nextInt() % 10);
      randomTwo = Math.abs(rand.nextInt() % 10);

      product = randomOne * randomTwo;

      System.out.println("How much is " + randomOne + " times " + randomTwo + "?");
      userInput = scan.nextInt();

      while (userInput != -1 && product != userInput) {
        System.out.println("No. Please try again.");
        System.out.println("How much is " + randomOne + " times " +
            randomTwo + "?");
        userInput = scan.nextInt();
      }
      if (product == userInput) {
        System.out.println("Very Good!");
      } else {
        playingGame = false;
      }
    }

    scan.close();
  }
}

推荐阅读