让用户猜测一个随机数并循环直到正确为止

时间:2018-11-11 21:47:45

标签: java

我已经尝试了好几个小时,但由于某种原因我无法显示输出,同时显示“对不起那个数字太高”和“对不起那个数字太低”而没有循环或使用一个答案。

import java.util.*;

public class RandomNumbers {

    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        Random numGen = new Random();
        int RanNum = numGen.nextInt(20) + 1; 
        System.out.println("Guess what number im thinking of");
        int num ;
        num = keyboard.nextInt();
        if (num == RanNum)
            System.out.println("Good Job");
        else if  (num > RanNum)
            System.out.println("Sorry that number is too high");
        else if (num < RanNum);
        System.out.println("Sorry that number is too low");

    }
}

3 个答案:

答案 0 :(得分:3)

else if (num < RanNum)之后的分号是您的问题

答案 1 :(得分:0)

如果您在第三个if末尾放了分号。 您仍然应该会收到“ Good Job”消息。

public static void main(String[] args) 
{
    Scanner keyboard = new Scanner(System.in);
    Random numGen = new Random();
    int RanNum = numGen.nextInt(1) + 1; 
    System.out.println("Guess what number im thinking of");
    int num ;
    num = keyboard.nextInt();
    if (num == RanNum)
        System.out.println("Good Job");
    else if  (num > RanNum)
        System.out.println("Sorry that number is too high");
    else if (num < RanNum)
        System.out.println("Sorry that number is too low");

}

编辑:对不起,为时已晚:)

答案 2 :(得分:0)

要不断提示用户,请使用while循环检查他们是否猜对了。我也建议添加另一个输入检查,以使退出不正确。简短示例:

boolean incorrect = true;
while(incorrect) {

  //Code to prompt for input

  if(userIsCorrect || input == -1){
    incorrect = false;
    //Program will exit loop when this is set to false
  }
}