简体   繁体   English

对于循环更改随机数

[英]For Loop Changes randomnumber

My RandomNumber value changes in my for loop statement. 我的RandomNumber值在我的for循环语句中更改。 This prevents the program from actually matching the RandomNumber generated with the number entered by the user. 这样可以防止程序将生成的RandomNumber与用户输入的数字实际匹配。 How can I modify my for loop so that it does not affect the RandomNumber? 如何修改我的for循环,使其不影响RandomNumber?

This is the java code I did in NetBeans; 这是我在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;
            }
        }
    }
}

You have to use a different variable for counting in the loop. 您必须在循环中使用其他变量进行计数。 You're assigning to randNum in 您正在分配给randNum

for (randNum = 0; randNum <3; randNum = randNum + 1)
for (randNum = 0; randNum <3; randNum = randNum + 1)

改成

for (int i= 0; i<3; i = i+ 1)

Here: Please note that I moved the Scanner outside the loop since you do not need to have it created multiple times. 此处:请注意,由于无需多次创建扫描仪,因此我将其移动到了循环之外。

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);
    }
  }
}

I have just assign another variable for for loop. 我刚刚为for循环分配了另一个变量。

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

      if (rand1 == guessNum)
      { 
                System.out.println("You Guessed it!");
                        break;
      }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM