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
);
}
}