user2179615
user2179615

Reputation: 127

Random numbers while loops

I am new to java and i am so close to the answers.i hope that i can have some hints but not the full answer.I will prefer to derive the logic out on my own.

/*
Write a method named makeGuesses that will guess numbers
between 1 and 50 inclusive until it makes a guess of at least 48.
It should report each guess and at the end should report
the total number of guesses made. Below is a sample execution:
*/

guess = 43
guess = 47
guess = 45
guess = 27
guess = 49
total guesses = 5

public void makeGuesses(){
    Scanner sc=new Scanner(System.in);
    Random rnd=new Random();
    int i=1
    int counter=0;

   while(i>=1 && i<=50){

        i=rnd.nextInt();
        System.out.println("guess = " + i);
         counter++;


    }
    System.out.print("total guesses = "+ counter);
}

What's wrong with my code?I realised although i fix my i to be between 1 and 50,it still exceeds.

Upvotes: 0

Views: 8411

Answers (1)

TheEwook
TheEwook

Reputation: 11117

You must specify the bound in your rnd.nextInt(); in your case I guess

rnd.nextInt(50) + 1; // (1 - 50)

and review your condition otherwise your program will never stop

while(i>=1 && i<=50)

Have a look at the documentation:

http://docs.oracle.com/javase/6/docs/api/java/util/Random.html

Following is the declaration for java.util.Random.nextInt() method.

public int nextInt(int n)

Parameters n--This is the bound on the random number to be returned. Must be positive.

Return Value The method call returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and n (exclusive).

Upvotes: 2

Related Questions