我想不通使用while循环将-1实现为哨兵值。

时间:2019-02-08 18:55:00

标签: java

我不知道使用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,程序都应停止。

1 个答案:

答案 0 :(得分:0)

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

return