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 :-)