java exercise 3
guess the number
/*
Create a class Game, which allows a user to play "Guess the Number"
game once. Game should have the following methods:
1. Constructor to generate the random number
2. takeUserInput() to take a user input of number
3. isCorrectNumber() to detect whether the number entered by the user is true
4. getter and setter for noOfGuesses
Use properties such as noOfGuesses(int), etc to get this task done!
*/
package com.company;
import java.util.Random;
import java.util.Scanner;
class Game{
int compNumber;
private int noOfGuesses = 0;
Game(){
Random random = new Random();
compNumber = random.nextInt(100);
}
/*void userInput(int n){
int userInput = n;
}
I can't find any use of this, so commented it.
*/
boolean isCorrect(int n){
if(compNumber == n){
return true;
}
else
return false;
}
void setNumOfGuesses(){
noOfGuesses++;
}
int getNumOfGuesses(){
return noOfGuesses;
}
}
public class cwh_exercise3_Guess_Number_oops {
public static void main(String[] args) {
System.out.println("----------GUESS THE NUMBER----------");
Game guessGame = new Game();
Scanner input = new Scanner(System.in);
int guess = input.nextInt();
guessGame.setNumOfGuesses();
while(!guessGame.isCorrect(guess)){
if(guess < guessGame.compNumber){
guessGame.setNumOfGuesses();
System.out.println("Number is greater than " + guess + ", Guess Again.");
guess = input.nextInt();
}
else if(guess > guessGame.compNumber){
guessGame.setNumOfGuesses();
System.out.println("Number is less than " + guess + ", Guess Again.");
guess = input.nextInt();
}
}
System.out.println("You have guessed the correct number, that is : " + guess);
System.out.println("No of Guess you took: " + guessGame.getNumOfGuesses());
}
}
Comments
Post a Comment