使用if语句和for循环Java的随机数猜测游戏

时间:2014-12-16 05:20:05

标签: java loops if-statement for-loop random

我的名字是费明。我是这个论坛的新手,我也在学习Java,成为一名Java开发人员。我被困在任务上,我希望得到任何人的帮助。这是描述和代码 在for块中使用if语句,确定 是否randNum和guessNum相等。

public class GuessGame {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {


     int randNum , guessNum ;
     //Generates a random number from 1 to 10
     randNum = new java.util.Random().nextInt(10) + 1;
     System.out.println("Im thinking of a number from 1 to 10");

  for (guessNum = 0; guessNum <= 10; guessNum ++){

      java.util.Scanner scan = new java.util.Scanner(System.in);
      guessNum = scan.nextInt();

      if (guessNum == randNum) {
           System.out.println("you guess" + guessNum );
    }
  } 
}

}

更新了代码

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

 public class NumberGuess {

    public static void main(String[] args) {

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

        System.out.println("Im thinking of a number from 1 to 10");
        int number = scan.nextInt(10);
         //Generates a random number from 1 to 10
        int number2 = rand.nextInt(10)+1;
        System.out.println("you enter the number" + " " + number);


        for (int counter = -1; counter < 3; counter ++ ){
             if(number!= number2)
               System.out.println("and your random number is:" + " " + number2 + " " + "please try again"); 
             else 
                 System.out.println("your guess number is equal to the random number Good job guessing");

             break;
         }

    }
  } 

2 个答案:

答案 0 :(得分:0)

for循环由guessNum变量控制。在循环中,当您执行此操作时,您将重新分配该变量的值:

guessNum = scan.nextInt();

因此,您可能会获得一个不一致的循环次数,因为您正在更改循环所依赖的变量以进行控制。

鉴于此变量的名称,我怀疑您最初打算将其用于存储用户的输入。如果是这种情况,我会改变你的for循环以使用不同的变量,如下所示:

for (int guessCount = 0; guessCount < 10; guessCount++){

另请注意,您的病情最初为<= 10;因为你的计数变量从零开始,这将允许用户11猜测,而不是10(因为0到10包括= 11)。假设你想要10个猜测,你需要检查少于10个(因为0..10独占= 10)。

答案 1 :(得分:0)

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

 public class NumberGuess {

    public static void main(String[] args) {

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

        System.out.println("Im thinking of a number from 1 to 10");
        int number = scan.nextInt(10);
         //Generates a random number from 1 to 10
        int number2 = rand.nextInt(10)+1;
        System.out.println("you enter the number" + " " + number);


        for (int counter = -1; counter < 3; counter ++ ){
             if(number!= number2)
               System.out.println("and your random number is:" + " " + number2 + " " + "please try again"); 
             else 
                 System.out.println("your guess number is equal to the random number Good job guessing");

             break;
         }

    }
  }