My homework is to make a program that calculates the total value of products sold. It works, but I use the if
statement because it was asking for the quantity on the output before ending the loop. And for the same reason, I couldn't make the program ask the user again to enter a number from 1 to 5.
import java.util.Scanner;
public class Sales {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double sum = 0;
int n = -1 ;
while(n !=0 ) {
System.out.println("Enter product number 1-5 (Enter to stop)");
n = input.nextInt();
if (n==0)
break;
System.out.println("Enter quantity of product");
int q = input.nextInt();
switch (n) {
case 1:
sum += 2.98*q;
break;
case 2:
sum += 4.50*q;
break;
case 3:
sum += 9.98*q;
break;
case 4:
sum += 4.49*q;
break;
case 5:
sum += 6.87*q;
break;
default:
sum += 0;
break;
}
} System.out.printf("Total cost is $%.2f",sum);
}
}
2 Answers 2
Prefer not to use single characters as variable names (except for simple loop counters). Saving a few keystrokes is not worth it if your readers cannot understand your code.
Based on the context, it looks like
n
andq
should respectively be namedproductNumber
andproductQuantity
.The
sum += 0
in thedefault
looks unnecessary. Just remove it if so, even if it's only there to have thedefault
do something. Keep things simple.
-
3\$\begingroup\$
Saving a few keystrokes is not worth it if your readers cannot understand the code
- well said! \$\endgroup\$Mathieu Guindon– Mathieu Guindon2013年11月19日 02:33:51 +00:00Commented Nov 19, 2013 at 2:33
A slighty longer answer:
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* Calculates the sum of given products.
*/
public class ProductSumCalculator {
/**
* Represents a product with a price.
*/
protected enum Product {
APPLE(1, "Apple", 2.98d),
BANANA(2, "Banana", 4.50d),
MANGO(3, "Mango", 9.98d),
PINEAPPLE(4, "Pineapple", 4.49),
CHERRY(5, "Cherry", 6.87);
protected double price;
protected int productNumber;
protected String productTitle;
private Product(int productNumber, String productTitle, double price) {
this.price = price;
this.productNumber = productNumber;
this.productTitle = productTitle;
}
public static Product getByNumber(int number) {
for (Product product : values()) {
if (product.productNumber == number) {
return product;
}
}
return null;
}
@Override
public String toString() {
return productNumber + " - " + productTitle + " - " + String.format("$%.2f", price);
}
}
/**
* @param args
*/
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
double sum = 0.0d;
int input = -1;
while (input != 0) {
System.out.println("Please make your choice: ");
for (Product product : Product.values()) {
System.out.println(product);
}
System.out.println("0 - Quit and show sum");
input = readNumberInput(scanner);
if (input == 0) {
break;
}
if (input != -1) {
Product product = Product.getByNumber(input);
if (product == null) {
System.out.println("The entered product number was not correct. Please try again.");
} else {
System.out.println("Enter quantity of product [" + product.productTitle + "]:");
input = readNumberInput(scanner);
if (input > 0) {
sum += product.price * input;
}
}
}
}
System.out.println("Total sum of all the chosen products is: " + String.format("$%.2f", sum));
} finally {
scanner.close();
}
}
/**
* Reads a number from a scanner instance and catches erroneous input.
*
* @param scanner
* @return
*/
private static int readNumberInput(Scanner scanner) {
try {
return scanner.nextInt();
} catch (InputMismatchException ex) {
String inputString = scanner.next();
System.out.println("Input [" + inputString + "] was not correct. Please choose a number.");
return -1;
}
}
}
Let's run over this code, shall we:
- I created an enum of 'Product' so that you can easily add/remove products and change their number, title or price and so that your main code doesn't have to change when adding/removing products
- Overridden the toString method of a Product so you can print them out in the program
- Validate the input from the user (ALWAYS validate input from the user)
- Closed the scanner instance (ALWAYS close your resources when possible)
- Added more clear instructions for the user with better guidance through the 'program'
I know it's a stupid little program, but it's an easy example of how your code will be able to change more easily later on, by adding/removing products, validating user input, etc... The one thing I could have added is more documentation, but in this case it's very trivial :-)