The program asks the user to enter values for items bought, the price of each item, the GST rate, the QST rate. The program calculates the subtotal based on these inputs. For every invalid input entered by the user the program will prompt the user to re-enter that value until it is a valid input. Items bought must be between 1 and 10. The price of each item must be between 1 and 1000. The GST must be between 0 and 14. The QST must be between 0 and 17.
Im wondering if there's a way I can make this code more efficient by including more methods or anything else. Thanks!
import java.util.Scanner;
public class Taxes{
public static void main(String[] args){
double subtotal = 0;
int errors = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the number of items bought (1-10): ");
int num_items = scan.nextInt();
while (num_items < 1 || 10 < num_items){
errors += 1;
System.out.println("Please enter the number of items bought (1-10): ");
num_items = scan.nextInt();
}
for (int i = 1; i <= num_items; i++){
Scanner scn = new Scanner(System.in);
System.out.println("Please enter the price of item " + i);
Double item_cost = scn.nextDouble();
while (item_cost < 1 || 1000 < item_cost){
errors += 1;
System.out.println("Please enter the price of item " + i);
item_cost = scn.nextDouble();
}
subtotal += item_cost;
}
System.out.println("Please enter the tax rate of GST in %: ");
double gRate = scan.nextDouble();
while (gRate < 0 || 14 < gRate){
errors += 1;
System.out.println("Please enter the tax rate of GST in %: ");
gRate = scan.nextDouble();
}
System.out.println("Please enter the tax rate of QST in %: ");
double qRate = scan.nextDouble();
while (qRate < 0 || 17 < qRate){
errors += 1;
System.out.println("Please enter the tax rate of QST in %: ");
qRate = scan.nextDouble();
}
calculate(subtotal, gRate, qRate, errors);
}
public static void calculate(double subtotal, double gRate, double qRate, int errors)
{
double gst = subtotal * (gRate/100);
double qst = (subtotal + gst) * (qRate/100);
double total = subtotal + gst + qst;
System.out.println("GST: " + gst);
System.out.println("QST: " + qst);
System.out.println("Subtotal: " + total);
System.out.println("You entered " + errors + " invalid inputs");
}
}