如何在用户输入-1之前循环此代码?

时间:2015-11-10 00:39:55

标签: java

我是java的新手,我想知道如何循环这段代码,直到某人输入-1以及如何添加"超出范围"如果用户输入的数字不在0-100之间?

到目前为止,这是我的代码:

import java.util.Scanner;
public class Question2 {

   public static void main(String args[]) {
      Scanner keyboard = new Scanner(System.in);
         int count = 0;
         int a = 1 + (int) (Math.random() * 99);
         int guess = 0;

      System.out.println("Welcome to the Number Guessing Game");
      System.out.print("Guess a number between 0 and 100 or enter -1 to end: ");

      while (guess != a) {
        guess = keyboard.nextInt();
         count++;
        if (guess > a) {
            System.out.print("The number is lower. Try again: ");
        } 
        else if (guess < a) {
            System.out.print("The number is higher. Try again: ");
        }
        else if (guess == a) {
        System.out.println("Congratulations. You guessed the number in "
        + count + " tries!");
       }
    }

   }
}

2 个答案:

答案 0 :(得分:0)

您可以检查for循环中的边界。为了停止进一步检查,您可以通过continue调用迭代到下一个循环。否则,如果你真的想要突破循环,请使用break调用(对于-1情况)。

while (guess != a) {
    guess = keyboard.nextInt();
     count++;
    if (guess < 0 || guess > 100){
        if(guess == -1)
             break;
        System.out.println("Out of bounds");
        continue;
    }
    if (guess > a) {
        System.out.print("The number is lower. Try again: ");
    } 
    else if (guess < a) {
        System.out.print("The number is higher. Try again: ");
    }
    else if (guess == a) {
    System.out.println("Congratulations. You guessed the number in "
    + count + " tries!");
 }
 System.out.println("Thank-you for playing the game!!");

答案 1 :(得分:0)

您希望执行某些代码,而某些代码不是= -1。在java中,我们使用

!=

表示不相等。所以,请记住这个代码:

do{

        guess = keyboard.nextInt();
         count++;
        if (guess > a) {
            System.out.print("The number is lower. Try again: ");
        } 
        else if (guess < a) {
            System.out.print("The number is higher. Try again: ");
        }
        else if (guess == a) {
        System.out.println("Congratulations. You guessed the number in "
        + count + " tries!");
       }

   }
}
\\Here comes the **while**

} while (guess != a && keyboard.in != -1)

while表示当guess不是 AND 时,用户没有输入-1。这是可以执行操作的唯一方式。

多数民众赞成!我建议你阅读更多关于数学运算和循环的内容。

祝你好运,

{Rich}