Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVA

guessing game in java

package com.company;

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

class Game {
    public int noOfGuess;
    public int compGuess;
    public int takeUserInput;

    Game() {
        Random random = new Random();
        this.compGuess = random.nextInt(100);
    }

    public int getNoOfGuess() {
        return noOfGuess;
    }

    public void setNoOfGuess(int noOfGuess) {
        this.noOfGuess = noOfGuess;
    }

    public void takeUserInput() {
        System.out.println("Enter your Guess");
        Scanner scanner = new Scanner(System.in);
        takeUserInput = scanner.nextInt();
    }

    public boolean checkingTheGame() {
        noOfGuess = 1 + noOfGuess;
        if (takeUserInput == compGuess) {
            System.out.println("YOU WON!!");
            return true;
        } else if (takeUserInput < compGuess) {
            System.out.println("Your guess is TOO LOW!!");
        } else {
            System.out.println("Your guess is TOO HIGH!!");
        }
        return false;
    }

}

public class NumberGuessingGameInOOP {
    public static void main(String[] args) {
        Game game = new Game();
        System.out.println("Welcome to the guessing game");
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your name");
        String playerName = scanner.nextLine();
        boolean gamePlay = false;
        while (!gamePlay) {
            game.takeUserInput();
            gamePlay = game.checkingTheGame();
        }
        System.out.println(playerName + " your point " + game.getNoOfGuess());


    }
}
//Game should have the following methods:
//Constructor to generate the random number
//takeUserInput() to take a user input of number
//isCorrectNumber() to detect whether the number entered by the user is true
//getter and setter for noOfGuesses
// Clean code
 
PREVIOUS NEXT
Tagged: #guessing #game #java
ADD COMMENT
Topic
Name
5+6 =