HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Car Savings Calculator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
savingscalculatorcar

Problem

I've created a second 'calculator-like' program, this time using the JOptionPane rather than typing in the console. At the moment the code looks to have a lot of repetition so I'm looking to simplify it; any advice and suggestions would be great!

import javax.swing.JOptionPane;

public class SaveCalc {

    public static void main(String[] args) {

        //Text prompts to collect data
        String carCost = JOptionPane.showInputDialog("What is the total cost of the car?");

        String insCost = JOptionPane.showInputDialog("What is the yearly cost of the insurance?");

        String manCost = JOptionPane.showInputDialog("How much would you like to save for maintenance?");

        String saveMonth = JOptionPane.showInputDialog("How much will you be saving each month?");

        //Converts string inputs to Doubles
        double carCostP = Double.parseDouble(carCost);
        double insCostP = Double.parseDouble(insCost);
        double manCostP = Double.parseDouble(manCost);
        double saveMonthP = Double.parseDouble(saveMonth);

        //Calculates the total cost and the months to save
        double costTotal = carCostP + insCostP + manCostP;
        double months = costTotal / saveMonthP;

        //Converts the months value to an integer
        int monthsP = (int) months;

        System.out.printf
        ("With a saving of \u00A3%5.2f each month and a total cost of \u00A3%5.2f it will take " 
        + monthsP 
        + " months to save up.",saveMonthP,costTotal);
    }
}

Solution

Do not include types in variable names

carCostP
       ^


Remove that P (probably stands for a number type?) the compiler takes care of types for you.

Avoid so many variables

You can avoid those four variables altogether, you may just convert to double as soon as you read the vars, like this:

double carCost = Double.parseDouble(
     JOptionPane.showInputDialog("What is the total cost of the car?"));

Code Snippets

carCostP
       ^
double carCost = Double.parseDouble(
     JOptionPane.showInputDialog("What is the total cost of the car?"));

Context

StackExchange Code Review Q#105255, answer score: 7

Revisions (0)

No revisions yet.