5
\$\begingroup\$

I've been learning Java for a very short period of time but with a couple of pointers, I've been able to put this simple VAT calculator together. If anyone could offer any ideas for improvement that'd be great!

import java.text.DecimalFormat;
import java.util.Scanner;

public class TaxCalc {

    public static void main(String[] args) {

        System.out.println("Welcome to the simple VAT Calculator.");
        System.out.println("To Calculate VAT Payable and the ex-VAT Cost type the total cost below:");
        System.out.println("----------");
        Scanner cost = new Scanner (System.in);
        double totalCost = cost.nextDouble();

        cost.close();

        System.out.println("----------");
        double exVat;
        exVat = (totalCost * 0.8);
            DecimalFormat df = new DecimalFormat("0.00");
            String exVatStr = df.format(exVat);
            exVat = Double.valueOf(exVatStr);


        double vat;
        vat = totalCost - exVat;
            DecimalFormat df2 = new DecimalFormat("0.00");
            String vatStr = df2.format(vat);
            vat = Double.valueOf(vatStr);

        System.out.println("The VAT payable is £" + vatStr);
        System.out.println("The ex-VAT Cost is £" + exVatStr);

    }
}
\$\endgroup\$
3
\$\begingroup\$

I second @Caridorc's recommendation. In general anytime you find repetitive code it's a sign to extract the common parts into a routine.

Use escape characters

Additionally, rather than subsequent calls to println use escape characters and concatenate the designated strings. You also want to use an escape to specify the Unicode for the pound symbol to ensure it works across platforms.

With these suggestions your two primary calls would become:

System.out.println(
    "Welcome to the simple VAT Calculator"
    + "\nTo Calculate VAT Payable and the ex-VAT Cost type the total cost below:"
    + "\n----------"
);

and

System.out.println(
    "The VAT payable is " + vatStr
    + "\n" + "The ex-VAT Cost is \u00A3" + exVatStr
);

\u00A3 is the Java Unicode specification for the pound symbol.

Declare and instantiate in one step

For exVat and vat you declare the type, and then set the value on another line. Might as well just combine steps since there's no reason to separate them in this case. I'm sure you understand this since you've done so for your Scanner and totalCost variable.

Make a habit of using try-with-resources

On topic of your scanner, good job closing it. It's something oft missed even with non-beginners. For future reference, it's ideal to use try-with-resources to ensure that is handled, and is also an example of where you may want to separate declaration and instantiation.

 double totalCost;
 try (Scanner cost = new Scanner(System.in)) {
    totalCost = cost.nextDouble();
 }

When formatting is the goal

If formatting regardless of input is your goal, you should use String's static format method and/or rather than calling print use printf

The way to use it is to add in a reference to what you're calling in the string, and the references themselves afterwards, in order.

e.g. for your purposes,

System.out.printf(
  "----------%nThe VAT payable is %10.2f%nThe ex-VAT Cost is %10.2f\u00A3", vat, exVat
);

Here the % is used for the references that follow, the .2 specifies the number of decimal places, and the 10 reserves up to 10 spaces for alignment. Read more about this here.

One benefit of using printf directly is that you don't need to use the previous routine and your entire program becomes:

import java.util.Scanner;

public class Calculator {
  public static void main(String[] args) {
    System.out.println(
      "Welcome to the simple VAT Calculator"
      + "\nTo Calculate VAT Payable and the ex-VAT Cost type the total cost below:"
      + "\n----------"
    );

    double totalCost;

    try (Scanner cost = new Scanner(System.in)) {
      totalCost = cost.nextDouble();
    }

    double exVat = (totalCost * 0.8);
    double vat = totalCost - exVat;

    System.out.printf(
      "----------%nThe VAT payable is %10.2f%nThe ex-VAT Cost is %10.2f\u00A3", vat, exVat
    );
  }
}
\$\endgroup\$
2
\$\begingroup\$

You can simplify your code by extracting repetition to a method:

public static double round2(double n) {
    return Double.valueOf((new DecimalFormat("0.00")).format(n));
}

Your main function is now much smaller:

public static void main(String[] args) {

    // The same ...


    double exVat = (totalCost * 0.8);
    double vat = totalCost - exVat;

    System.out.println("The VAT payable is £" + (round2(vat)));
    System.out.println("The ex-VAT Cost is £" + (round2(exVat)));

}
\$\endgroup\$
  • \$\begingroup\$ Using this solution, how would I go about solving the issue of the two printed prices not being correctly formatted for a currency value? i,e; When "100" is used as the input value, the following is output: "The VAT payable is £20.0 The ex-VAT Cost is £80.0" \$\endgroup\$ – TomConibear Sep 16 '15 at 15:22
  • \$\begingroup\$ @TomConibear you mean too many trailing zeros? \$\endgroup\$ – Caridorc Sep 16 '15 at 15:36
  • \$\begingroup\$ Not too many, too few. For it to be a standard currency value, I'd want it to have 2 decimals places in all cases. \$\endgroup\$ – TomConibear Sep 16 '15 at 15:37
  • \$\begingroup\$ @TomConibear this is a good resource stackoverflow.com/questions/153724/… \$\endgroup\$ – Caridorc Sep 16 '15 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.