设置sentinel值java代码

时间:2015-11-12 21:15:19

标签: java

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

公共类ArithmeticGame {

static int right = 0;
static int wrong = 0;
static int total = 0;
static int per = 0;

public static void main(String[] args) {

    Scanner s = new Scanner(System.in);
    Random num = new Random();
    Random num1 = new Random();
    int r = 0;

    while (r != 999) {
        total++;
        per = (right / total) * 100;

        int a = num.nextInt(20);
        int b = num1.nextInt(20);

        int sum = a + b;
        System.out.println(" \n                                     ARITHETIC GAME!");
        System.out.println("What is the sum of " + a + " + " + b + " ?");
        r = s.nextInt();

        if (r == sum) {
            System.out.println("Your answer is correct.");
            right++;
        }

        if (r != sum) {
            System.out.println("OOPS! Your answer is Wrong");
            wrong++;
        }
        System.out.println("So far you have " + right + " right answers " + wrong + " wrong answers out of  total "
                + total + " questions");
    }
}

} 我需要设置sentinel值,这样当我输入999时,程序应该终止,响应999不应该计入最终值。

1 个答案:

答案 0 :(得分:1)

将循环更改为

while(true) {
....
}

然后在行 r = s.nextInt(); 之后但在检查它是对还是错之前,添加:

if(r == 999) {
  break;
}