Hi,
I've seen a program called guessing game in a book. There are basically 3 players in the game. The program generates a random number and the players guess for that number. I wrote my own code for it and need your advice on how to improve the Object Oriented concept in the program. Please tell me the design flaws in my program. Please find the program below:
NOTE: I've named the classes as they were in the book itself, but the code is different.
GameLauncher.class:- This is the main class
package com.XXX;
public class GameLauncher {
/**
* @param args
*/
public static void main(String[] args) {
GuessGame game = new GuessGame();
game.startGame();
}
}
Player.class: - In this class the player guesses the number and it is compared to the targetnumber.
package com.XXX;
public class Player {
static int number;
public boolean guess(int targetNumber)
{
number= (int) (Math.random()*10);
System.out.println("the number guessed is"+number);
if(number==targetNumber)
{
return true;
}
else
return false;
}
}
GuessGame.class : - This class generates the targetnumber.
package com.vamsi;
public class GuessGame {
Player player1;
Player player2;
Player player3;
public void startGame()
{
player1 = new Player();
player2 = new Player();
player3 = new Player();
int targetNumber =(int) (Math.random() *10);
System.out.println("the number to be guessed is "+targetNumber);
while(true)
{
boolean result1 = true;
boolean result2 = true;
boolean result3 = true;
result1 = player1.guess(targetNumber);
result2 = player2.guess(targetNumber);
result3 = player3.guess(targetNumber);
if(result1==true)
{
System.out.println("the correct number is guessed by player1. The number is "+Player.number);
break;
}
else if(result2==true)
{
System.out.println("the correct number is guessed by player2. The number is "+Player.number);
break;
}
else if(result3==true)
{
System.out.println("the correct number is guessed by player3. The number is "+Player.number);
break;
}
/*else
{
System.out.println("The number guessed is"+Player.number);
}*/
}
}
}
Thanks,
NewCoder :)