Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying the MVC Concept in JAVA

Tags:

java

Good day!

With regards to my previous post, to adapt to the concept of MVC as suggested, I changed my code and included an IO class as follows:

  public class IO {
        public void output(String msg) {
            JOptionPane.showMessageDialog(null, msg);
        }

        public String input(String prompt) {
            return JOptionPane.showInputDialog(prompt);
        }

        public int inputInt(String prompt) {
            return Integer.parseInt(input(prompt));
        }
    }


   public class GuessGame {

    private int numberToGuess;
    private ArrayList<Player> player;
    private IO io = new IO ();

    public void acceptPlayers(){
        int num_players = io.inputInt("Enter number of players");  
        player = new ArrayList<Player>(num_players);
        for (int i = 0; i < num_players; i++) {
            player.add(new Player(io.input("Enter Player " + (i+1) + " Name: ")));
        }
    }

    public void startGame() {
        numberToGuess = (int) (Math.random() * 10);
        while (true) {
            for (Player curPlayer : player) {
                if (curPlayer.guessNumber() == numberToGuess) {
                    declareWinner(curPlayer);
                    return;
                }
                io.output(curPlayer.getPlayerName() + "'s Guess is Wrong!");
            }
        }
    }

    private void declareWinner(Player player) {
        io.output(player.getPlayerName() + " Wins!");
    }
}

Is this correct? How can I improve my code? Thank you.

like image 975
newbie Avatar asked Jul 31 '26 06:07

newbie


2 Answers

IO class rappresent your View in MVC model.

GuessGame class have to much responsability, this class is for you both the model and the controller, you have to split it.

You can create a Game class wich have as status numberToGuess and ArrayList player; and for method addPlayer() and start()

Than you can have a class GameControlled that have for status IO class and a Game class. and for method acceptPlayers(),*startGame()*,declareWinner(Player player).

like image 187
Irene Audrito Avatar answered Aug 02 '26 20:08

Irene Audrito


In the above code, you cannot change the view i.IO from a graphical interface to a command line interface. If you change the IO to an interface and a class GraphicalIO to show graphical interface and another class CommandLineIO to show command line interface you can make the best use of OOP concepts.

Also with respect to MVC pattern If you take the IO for generating the view and GuessGame as a model and controller, since it has the logic and the program control, it is still not cleanly separated.The guess game is tightly coupled to IO object which is again tightly coupled to Graphical view.

like image 30
Siva Avatar answered Aug 02 '26 20:08

Siva