0

I'm new to programming and while working on the Head First Java book I wanted to make a simple program, but there are some points I can't do. What I want the program to do is keep an integer number between 0 and 100 randomly and the user tries to find it. If the user finds the number, congratulations will appear on the screen. If not, it will ask for a new prediction. The code I wrote is below:

package Intro;
import java.util.Scanner;

public class GuessingGame {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Please enter a number: ");

        int prediction = input.nextInt();

        int number = (int) (Math.random());

        if (number==prediction) {

            System.out.println("Congratulations!");
        }

         else {

            System.out.println("Wrong answer! Try a new number: ");

        }
     

    }
}

The point I stuck is that I can't make the randomly stored number integer and a number between 0 and 100. Another point is that if the answer is wrong, the program does not want a new prediction.

  • 2
    Does this answer your question? [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – OH GOD SPIDERS Nov 02 '20 at 13:05
  • 1
    That's a fun little program that will get you familiar with conditions (`if` /`else`) and loops (most likely `while` or `do-while` loops for your particular problem). I think you need to further break down your program into elemental steps to identify which are the critical parts and how you need to combine them to create the desired behavior. – Patrick Nov 02 '20 at 13:09
  • @OHGODSPIDERS Yes, one of my questions. Thanks a lot, I solved it. But I still couldn't figure out that the program doesn't want a new prediction. –  Nov 03 '20 at 12:05

1 Answers1

0

Very simple read this documentation on Random: https://www.geeksforgeeks.org/java-math-random-method-examples/

// define the range 
        int max = 100; 
        int min = 1; 
        int range = max - min + 1; 
  
        // generate random numbers within 1 to 10 
        for (int i = 0; i < 10; i++) { 
            int rand = (int)(Math.random() * range) + min; 
  
            // Output is different everytime this code is executed 
            System.out.println(rand); 
        } 

Output:

6
8
10
10
5
3
6
10
4
2
LorenzoOtto
  • 112
  • 8
  • @GhostCat you are correct, see my edited question. – LorenzoOtto Nov 02 '20 at 13:08
  • This only answers one of the questions asked. Granted, StackOverflow questions should only be about a single problem but ... – Patrick Nov 02 '20 at 13:12
  • @LorenzoOtto Thank you for answer. I solved the problem you answered, but the program still doesn't want a new guess. –  Nov 03 '20 at 12:14