MVC Example

In this section, we will look at a first example that applies the MVC architecture.

Suppose we want to write a program that determines whether a number is divisible by nine. Numbers are divisible by nine if the sum of their digits are divisible by nine. We will write this program using MVC architecture. We will also allow the user to check whether 10 different numbers are divisible by 9.

Below is a list of the classes we’ll need, and which methods and fields will go there. It is a good idea to make a plan like this before you start writing any code.

IO (View component)

  • Scanner field/constructor to initialize
  • public int getNum()
  • public void displayDivisible(int num, boolean divisible)

Calculator (Model component)

  • public boolean getDivisible(int num)

Proj (Controller component)

  • Single main method that will call back and forth between IO and Calculator

MVC Implementation

Now, here’s the implementation of each class:

//In IO.cs
import java.util.*;

public class IO 
{
    private Scanner s;

    public IO() 
    {
        s = new Scanner(System.in);
    }

    public int getNum() 
    {
        System.out.print("Enter a positive integer: ");
        return s.nextInt();
    }

    public void displayDivisible(int num, boolean divisible) 
    {
        System.out.printf("%d is ", num);
        if (!divisible) System.out.print("not ");
        System.out.println("divisible by 9.");
    }
}

//In Calculator.cs
public class Calculator 
{
    public boolean getDivisible(int num) 
    {
        int sum = 0;
        while (num != 0) 
        {
            int digit = num%10;
            num = num/10;
            sum += digit;
        }

        if (sum % 9 == 0) return true;
        else return false;
    }
}

//In Proj.cs
public class Proj 
{
    public static void main(String[] args) 
    {
        //Create IO, Calculator objects
        IO io = new IO();
        Calculator calc = new Calculator();

        //Test 10 different numbers
        for (int i = 0; i < 10; i++) 
        {
            //Get input number
            int num = io.getNum();

            //Get divisibility
            boolean div = calc.getDivisible(num);

            //Display results
            io.displayDivisible(num, div);
        }
    }
}

The first thing you probably noticed on this example is that it is significantly more code than a single-class implementation would be. And you’re absolutely right – for this example, would make much more sense to just use a single class. However, as your programs get bigger, you will need to divide them up like this to be able to keep track of what’s going on. This example illustrates how to break things into several classes so that you’ll know how when you do get a big project.