Lasgo
Lasgo

Reputation: 11

For Loop Changes randomnumber

My RandomNumber value changes in my for loop statement. This prevents the program from actually matching the RandomNumber generated with the number entered by the user. How can I modify my for loop so that it does not affect the RandomNumber?

This is the java code I did in NetBeans;

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

Upvotes: 1

Views: 332

Answers (4)

Manish Doshi
Manish Doshi

Reputation: 1193

I have just assign another variable for for loop.

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

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

Upvotes: 1

Multithreader
Multithreader

Reputation: 878

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

Upvotes: 2

Maarty
Maarty

Reputation: 1190

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

change to

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

Upvotes: 3

LostBoy
LostBoy

Reputation: 958

You have to use a different variable for counting in the loop. You're assigning to randNum in

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

Upvotes: 6

Related Questions