user4179725
user4179725

Reputation:

Number Guessing Game Problems

So, I'm having trouble regarding a guessing game with numbers. I have a random number generated, but when I call my method into my main program to tell me if my guess is too big or too small, it doesnt seem to read the random number.

I.E. Random number generated is 12

Guess 3.
"Sorry, too big."
Guess 0
"Sorry, too small."

Any help would be appreciated.

Here's a snippet:

public static void main(String[] args) {

    Random rand = new Random();
    int rnum = rand.nextInt(49);
    System.out.print(rnum);

    for(int result = 0; result < 5; result++) {
        myMethod(result);
    }
}

public static void myMethod (int rnum) {
    Scanner input = new Scanner (System.in);
    System.out.println(" Guess a number between 0 and 49");
    int guess;
    guess = input.nextInt();

    if (guess > rnum) {
        System.out.print("Too big, sorry. Try again.");
    } else if (guess < rnum) {
        System.out.print("Too small, sorry. Try again.");
    } else if (guess == rnum) {
        System.out.print("You Win!");
    }
}

Upvotes: 0

Views: 140

Answers (3)

Fafore Tunde
Fafore Tunde

Reputation: 319

Try this

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

public class testt {

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Guess a number: ");
    int Guessed = sc.nextInt();
    int Rnumber;
    Random num = new Random();
    for (int i=1; i <= 25; i++)
    {
        Rnumber = num.nextInt(12); // Numbers will be around 12

    }

    if (Guessed >= 3) {
        System.out.println("Sorry, too big");
    }
        else 
            if (Guessed <= 0){
        System.out.println("Sorry, too small");
    }

                else 
                    System.out.println("You win");

}

}

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

In your code :

for(int result=0;result<5;result++){
    myMethod(result);
}

here you are sending result to myMethod instead of rnum.

 Random rand = new Random();
 int rnum = rand.nextInt(49);

when myMethod is called it will send 0,1,2,3,4 according to your code .

send

for(int result=0;result<5;result++){
    myMethod(rnum);
}

Instead of

for(int result=0;result<5;result++){
    myMethod(result);
}

Upvotes: 3

puzzlepalace
puzzlepalace

Reputation: 660

You are passing result to myMethod in your main method. I suspect that you want to pass rnum to that method instead as that is your psudeo random number.

Upvotes: 3

Related Questions