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);
}
}
JOptionPane.showInputDialog()
plusDouble.parseDouble()
into a separate function as suggested by TopinFrassi, but the primary benefit of that would be to refocus on the purpose of the particular piece of the code, not really to reduce repetition (because there is so little of that to begin with). \$\endgroup\$