0

here is the whole code how do I in this create random number so that numberneedingtobeguessed is generated randomly.

public class Guessing {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        @SuppressWarnings("resource")
        Scanner input = new Scanner(System.in);
        int number;
        int numberneedingtobeguessed = 26;
        int done = 1;

        System.out.println("I am thinking of a number in between 1 and 50 what is it?");
        while (done < 2) {
            number = input.nextInt();

            if (number < numberneedingtobeguessed) {
                System.out.println("Too low");
            }
            else if (number > numberneedingtobeguessed) {
                System.out.println("Too high");
            }
            else if (number == numberneedingtobeguessed) {
                System.out.println("You guessed correctly");
                done = done + 1;
            }
        }
    }
}
Karthik
  • 4,950
  • 6
  • 35
  • 65
  • The `Random()` class should do the work. I just wanted to tell you that typo such as : thisvariablecorrespondtoanumberwhichshouldbeguessed is definitely not clear. **1.** Use a specific style, such as : `int randomNumber = new Random();` or `int random_number = new Random();`. **2.** Keep your variable short but clear enough. – D.Naesuko Aug 15 '15 at 18:40
  • @D.Naesuko this is not my presentation that was just what I did to save time but this version isn't the las version at all – JulesTheGodOfMC Aug 15 '15 at 19:08

1 Answers1

1
import java.util.Random;

.........

Random ran = new Random();
int r = ran.nextInt(50) + 1;

This will generate a random number between 0 ... 49 and then add 1 at the end.

Luke Xu
  • 2,302
  • 3
  • 19
  • 43
  • Can you please explain how it works because when I search this up on the internet I don't understand (thanks it worked btw) – JulesTheGodOfMC Aug 15 '15 at 19:10
  • You're importing the class Random from java.util and then instantiating a "Random" object called ran. ran has a function called nextInt(int x) that will generate a random number for you. The random number generation is actually pseudo random and is based on a seed. – Luke Xu Aug 15 '15 at 19:11
  • ok but what id I wanted to do in between 1 and 100? – JulesTheGodOfMC Aug 15 '15 at 19:14
  • int r = ran.nextInt(100) + 1; – Luke Xu Aug 15 '15 at 19:16
  • @JulesTheGodOfMC No problem =) If this has solved your question please mark it as accepted! – Luke Xu Aug 15 '15 at 20:05