1

我的 for 循环语句中的 RandomNumber 值发生了变化。这可以防止程序实际将生成的 RandomNumber 与用户输入的数字相匹配。如何修改我的 for 循环,使其不影响 RandomNumber?

这是我在 NetBeans 中编写的 java 代码;

package numberguess;

/**
 * 
 * @author Marion
 */
public class NumberGuess {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) {
        int randNum = 0, guessNum = 0;
        // Generates a random number from 1 to 10
        randNum = new java.util.Random().nextInt(10) + 1;
        System.out.println("I am thinking of a random number from 1 to 10");
        for (randNum = 0; randNum < 3; randNum = randNum + 1) {
            System.out.print("Guess?");
            java.util.Scanner scan = new java.util.Scanner(System.in);
            guessNum = scan.nextInt();
            System.out.println("You guessed " + guessNum);
            if (randNum == guessNum) {
                System.out.println("You Guessed it!");
                break;
            }
        }
    }
}
4

4 回答 4

6

您必须使用不同的变量在循环中进行计数。您分配给 randNum in

for (randNum = 0; randNum <3; randNum = randNum + 1)
于 2013-07-03T12:22:54.097 回答
3
for (randNum = 0; randNum <3; randNum = randNum + 1)

改成

for (int i= 0; i<3; i = i+ 1)
于 2013-07-03T12:24:29.863 回答
2

这里:请注意,我将扫描仪移到循环之外,因为您不需要多次创建它。

public static void main(String[] args) {
    int randNum = randNum = new java.util.Random().nextInt(10) + 1;
    int guessNum = 0;
    java.util.Scanner scanner = new java.util.Scanner(System.in);

    System.out.println("I am thinking of a random number from 1 to 10");
    for(int i =0; i < 3; i++) {
        System.out.print("Guess?");
        guessNum = scanner.nextInt();
        if(randNum == guessNum) {
            System.out.println("You Guessed it!");
            break;
        }
        System.out.println("You guessed " + guessNum);
    }
  }
}
于 2013-07-03T12:28:32.067 回答
1

我刚刚为 for 循环分配了另一个变量。

for (int rand1 = 0; rand1 <3; rand1 = rand1 + 1)
{

      if (rand1 == guessNum)
      { 
                System.out.println("You Guessed it!");
                        break;
      }
}
于 2013-07-03T12:32:43.497 回答