How to build a Number Guessing Game in Java (Java Projects)

Here is a code of Number Guessing Game in Java that uses the 'javax.swing' package for the user interface. The game is a number guessing game where the user needs to guess a randomly generated number between 1 and 100.

java guessing game while loop

import java.util.Random;
import javax.swing.JOptionPane;

public class SimpleGuessingGame {
    public static void main(String[] args) {
        Random rand = new Random();
        int targetNum = rand.nextInt(100) + 1;
        boolean gameWon = false;

        while (!gameWon) {
            String input = JOptionPane.showInputDialog("Guess a number between 1 and 100:");
            int guess = Integer.parseInt(input);

            if (guess == targetNum) {
                JOptionPane.showMessageDialog(null, "Congratulations! You guessed the correct number: " + targetNum);
                gameWon = true;
            } else if (guess < targetNum) {
                JOptionPane.showMessageDialog(null, "Too low. Try again.");
            } else {
                JOptionPane.showMessageDialog(null, "Too high. Try again.");
            }
        }
    }
}

This program uses a while loop to repeatedly prompt the user for a guess until the correct number is guessed. The JOptionPane class is used to display dialogs for prompting the user for input and displaying the results of the game.

This code is just an example of a simple game, you can expand on it by adding more features, such as keeping track of the number of tries, or adding a score system and more.

It's a simple but good starting point to learn more about game development, I suggest you to start with this sample and add more features, or even to explore other libraries such as LibGDX and Slick2D, that are more focused on game development in java.
I trust this helps you! if you have any query you can ask me.

Post a Comment