0

I'm a beginner at java, and I've been given a project to write a simple java application that calculates the weekly Net Pay of a certain worker. Now I have written the code but in one class, I need to make this code based on the MVC architecture, can someone help?

Write an application that computes a worker’s weekly net pay. The inputs are the worker’s name, hours worked for the week, and hourly payrate. The output is the worker’s name and pay. The pay is computed as follows:

  • gross pay is hours worked multiplied by payrate. A bonus of 50% is paid for each hour over 40 that was worked.
  • a payroll tax of 22% is deducted from the gross pay

This is the code:

import javax.swing.*;
import java.text.*;
public class workersNetPay {

    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog("Write the name of the worker:");
        String hoursWorked = JOptionPane.showInputDialog("Write the hours worked during the week:");
        double hW = new Double(hoursWorked).doubleValue();
        String hourlyPayRate = JOptionPane.showInputDialog("Write the hourly pay rate:");
        double hpr = new Double(hourlyPayRate).doubleValue();
        double tax = 0.22;
        double grossPay = (hW*hpr)-((hW*hpr)*tax);
        double bonus = (grossPay * 0.5)+grossPay;
        String euro = "\u20AC";
        DecimalFormat formatter = new DecimalFormat("0.00");
        
        if (hW >  40) {
           JOptionPane.showMessageDialog(null, "Sir " + name + " your wage for this week is: " + formatter.format(bonus)+ euro);
        } else {
            JOptionPane.showMessageDialog(null,"Sir " + name + " your wage for this week is: " + formatter.format(grossPay)+ euro);
        }
    }
}

EDIT: Now I've written the model and the view but can someone help me with the controller

THE MODEL

public class Model {
        
    private double workersNetPay;
        
    public void calculate(double hoursWorked, double hourlyPayRate, double tax, double bonus, double grossPay) {

        tax = 0.22;
            
        if (hoursWorked> 40) {
           JOptionPane.showMessageDialog(null, bonus = (grossPay * 0.5) + grossPay);
        } else {
           JOptionPane.showMessageDialog(null,grossPay = (hoursWorked* hourlyPayRate)-((hoursWorked*hourlyPayRate)-tax));
        }
    }
    
    public double getWorkersNetPay() {
        return workersNetPay;
    }
}

THE VIEW

import java.awt.*;

import javax.swing.*;

public class view  {
    
    public String name() {
        
        String name = JOptionPane.showInputDialog("Write your name");
        
        return name;
    }
    
    public double hours() { 
        double h ;
        
        String hW = JOptionPane.showInputDialog("Write the hours worked during the week:");
        
        if (hW.matches("\\d+")) {
           h = Double.parseDouble(hW);
        } else {
            throw new IllegalArgumentException("You should write a number:");
        }
        
        return h;
    }
    
    public double hourlyPay() {
        double hp;
        
        String hpr = JOptionPane.showInputDialog("Write the hourly pay rate:");
        
        if (hpr.matches("\\d+")) { 
            hp = Double.parseDouble(hpr);
        } else {
             throw new IllegalArgumentException("You should write a number:");
        }
        
        return hp;
    }
        
    public void theResult(duoble result) { 
        JOptionPane.showMessageDialog(null, result, "Result", JOptionPane.INFORMATION_MESSAGE);
    }
}   

3 Answers 3

1

honestly, this seems like you should be doing some research. Start with "MVC java example".

All the best

Sign up to request clarification or add additional context in comments.

4 Comments

I have been doing research since yesterday, but I didn't find anything helpful, so I thought someone here might help me.
Specifically I am having trouble distinguishing which part of the code to put in me model, which one in the view and which one in the controller
Welcome to Stackoverflow, This does not provide an answer to the question, to maximise your chance of getting your answer accepted and upvoted, please Take the tour and read How do I write a good answer.
@amarinediary Thanks. A comment would have sufficed but I can't make them without enough reputation. Anyway I will keep you suggestion in mind for the next Answer. Thx
1

I don't think you get the concept of the MVC(Model, View, Controller) architecture.

The Model is a place of your code, where you keep, read and write data from - you don't do anything else like calculations and stuff.

On your place, I would create a class Worker with its needed private members where you keep the data of each worker. Next thing you could do is create some sort of data structure that it can store the instances of the Workers you have created, for e.g. a HashMap for fast access.

The View is a place of your code, where you only display information.

The Controller is the piece of your code that makes the connection between the Model and the View and keeps them separate, which is in the root of the SOLID Design principle.

Having these things covered up, your main should look something like this:

 //create our model
 WorkerModel model = new WorkerModel(); 
 // create our view
 WorkerView view = new WorkerView(); 
 // create our controller
 WorkerController controller = new WorkerController(model, view); 
 Worker worker = controller.createNewWorker("John");
 controller.calculateWorkerSalary(worker, hoursWorked, hourlyPayRate);
 controller.saveWorker(worker);
 controller.updateView();

On top of that, I would suggest you to follow the convention of always writing your java classes with uppercase("view" -> "View"), take a style of writing your bracers on the same line or new line, but not both and always keep your closing bracer on new line! It would make your code more pleasant to read!

2 Comments

where should I put the calculations
If you have created your Worker class, you should have the fields you need in it, e.g. hourlyPayRate, hoursWorked, bonus etc.
0

I reworked your code according to the MVC pattern. Here's the final JOptionPane.

Pay Stub

I created one model class, Worker.

public class Worker {
    
    private final double hoursWorked;
    private final double hourlyPay;
    private double grossPay;
    private double taxes;
    private double netPay;
    
    private final String name;

    public Worker(String name, double hoursWorked, 
            double hourlyPay) {
        this.name = name;
        this.hoursWorked = hoursWorked;
        this.hourlyPay = hourlyPay;
    }

    public String getName() {
        return name;
    }
    
    public void calculateGrossPay() {           
        if (hoursWorked > 40.0) {
            grossPay = 40.0 * hourlyPay + 
                    (hoursWorked - 40.0) * (hourlyPay * 1.5);
        } else {
            grossPay = hoursWorked * hourlyPay;
        }
    }
    
    public void calculateNetPay() {
        this.taxes = grossPay * 0.22;
        this.netPay = grossPay - taxes;
    }

    public double getHoursWorked() {
        return hoursWorked;
    }

    public double getHourlyPay() {
        return hourlyPay;
    }
    
    public double getGrossPay() {
        return grossPay;
    }

    public double getTaxes() {
        return taxes;
    }

    public double getNetPay() {
        return netPay;
    }
    
}

The Worker class is a plain Java class with getters and setters. The calculations are included in the model class because they are the same for each and every instance of Worker. While the calculation code is included in the model, the calculation code is performed in the controller method.

The view consists of the private methods of the WorkersPayExample class. The controller consists of the one public method, the createWorkerPayStub method. In this simple example, it's difficult to create a controller class.

Here's the complete runnable code.

import java.awt.Font;

import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class WorkersPayExample {

    public static void main(String[] args) {
        WorkersPayExample example = new WorkersPayExample();
        example.createWorkerPayStub();
    }
    
    public void createWorkerPayStub() {
        Worker worker = getWorkerInformation();
        worker.calculateGrossPay();
        worker.calculateNetPay();
        showResult(worker);
    }
    
    private Worker getWorkerInformation() {
        String name = getName();
        double hoursWorked = getHoursWorked();
        double hourlyPay = getHourlyPay();
        return new Worker(name, hoursWorked, hourlyPay);
    }
    
    private String getName() {
        String name = JOptionPane.showInputDialog("Write your name");
        return name;
    }
    
    private double getHoursWorked() {
        double hoursWorked;
        String hW = JOptionPane.showInputDialog("Write the hours "
                + "worked during the week:");

        if (hW.matches("\\d+")) {
            hoursWorked = Double.parseDouble(hW);
        } else {
            throw new IllegalArgumentException("You should write a number:");
        }

        return hoursWorked;
    }
    
    private double getHourlyPay() {
        double hourlyPay;
        String hpr = JOptionPane.showInputDialog("Write the hourly pay rate:");

        if (hpr.matches("\\d+")) {
            hourlyPay = Double.parseDouble(hpr);
        } else {
            throw new IllegalArgumentException("You should write a number:");
        }

        return hourlyPay;
    }
        
    private void showResult(Worker worker) {
        JTextArea textArea = new JTextArea(7, 30);
        textArea.setFont(new Font("monospaced", Font.PLAIN, 16));
        
        StringBuilder builder = new StringBuilder();
        builder.append("Pay stub for ").append(worker.getName());
        builder.append(System.lineSeparator());
        builder.append(System.lineSeparator());
        
        builder.append(String.format("%-20s", "Hours Worked"));
        builder.append(String.format("%9.2f", worker.getHoursWorked()));
        builder.append(System.lineSeparator());
        
        builder.append(String.format("%-20s", "Hourly Pay"));
        builder.append(String.format("%9.2f", worker.getHourlyPay()));
        builder.append(System.lineSeparator());
        
        builder.append(String.format("%-20s", "Gross Pay"));
        builder.append(String.format("%9.2f", worker.getGrossPay()));
        builder.append(System.lineSeparator());
        
        builder.append(String.format("%-20s", "Taxes"));
        builder.append(String.format("%9.2f", worker.getTaxes()));
        builder.append(System.lineSeparator());
        
        builder.append(String.format("%-20s", "Net Pay"));
        builder.append(String.format("%9.2f", worker.getNetPay()));
        builder.append(System.lineSeparator());
        
        textArea.setText(builder.toString());
        
        JOptionPane.showMessageDialog(null, textArea, "Result", 
                JOptionPane.INFORMATION_MESSAGE);
    }
    
    public class Worker {
        
        private final double hoursWorked;
        private final double hourlyPay;
        private double grossPay;
        private double taxes;
        private double netPay;
        
        private final String name;

        public Worker(String name, double hoursWorked, 
                double hourlyPay) {
            this.name = name;
            this.hoursWorked = hoursWorked;
            this.hourlyPay = hourlyPay;
        }

        public String getName() {
            return name;
        }
        
        public void calculateGrossPay() {           
            if (hoursWorked > 40.0) {
                grossPay = 40.0 * hourlyPay + 
                        (hoursWorked - 40.0) * (hourlyPay * 1.5);
            } else {
                grossPay = hoursWorked * hourlyPay;
            }
        }
        
        public void calculateNetPay() {
            this.taxes = grossPay * 0.22;
            this.netPay = grossPay - taxes;
        }

        public double getHoursWorked() {
            return hoursWorked;
        }

        public double getHourlyPay() {
            return hourlyPay;
        }
        
        public double getGrossPay() {
            return grossPay;
        }

        public double getTaxes() {
            return taxes;
        }

        public double getNetPay() {
            return netPay;
        }
        
    }
    
}

2 Comments

can you explain the meaning of builder.append and String.format("%-20s") and ("%9.2f"), this may be annoying to you but I'm a beginner and I want to know
@Albion2002: Sure. StringBuilder is a Java class that allows you to build Strings. You build strings by appending pieces of String to the StringBuilder. The String class has a format method that allows you to format a String. %-20s means left justify a String within 20 characters and %9.2f means right justify a floating point number and truncate it to two decimal places.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.