import java.io.*;
import java.util.*;
/**
* This class introduces and displays information about the product.
* @author Kubenov Anuar
* @data 14.02.2010
* @version 1.0.0
* @group IS-0906R
*/
public class ShoppingCartApplication {
private static BufferedReader stdIn =
new BufferedReader(new InputStreamReader(System.in));
private static PrintWriter stdOut =
new PrintWriter(System.out, true);
private static PrintWriter stdErr =
new PrintWriter(System.err, true);
private ShoppingCart cart;
/**
* It run a program.
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
ShoppingCartApplication application = new ShoppingCartApplication();
application.run();
}
/**
* Method performs actions when you select number of function.
*
* @throws IOException
*/
private void run() throws IOException {
cart = new ShoppingCart();
int choice = getChoice();
while (choice != 0) {
if (choice == 1) {
cart.addProduct(readProduct());
} else if (choice == 2) {
stdOut.println(cart.toString());
} else if (choice == 3) {
stdOut.println(cart.getTotalValue());
}
choice = getChoice();
}
}
/**
* Displays the four functions.
* @return input
* @throws IOException
*/
private int getChoice() throws IOException {
do {
int input;
try {
stdErr.println();
stdErr.println ("[0] Quit ");
stdErr.println ("[1] Add Product ");
stdErr.println ("[2] Display Products ");
stdErr.println ("[3] Display Total ");
stdErr.println ("choice>");
stdErr.flush();
input = Integer.parseInt(stdIn.readLine());
if (0 <= input && 3 >= input) {
return input;
} else {
stdErr.println("Invalid choice: " + input);
}
} catch (NumberFormatException nfe) {
stdErr.println(nfe);
}
} while (true);
}
/**
* Method intend for the option to add product.
*
* @return new name, quantity, price.
* @throws IOException
*/
private Product readProduct() throws IOException {
final String DELIM = "_";
String name = "";
int quantity = 0;
double price = 0.0;
try {
stdOut.print("product [name_qty_price]> ");
stdOut.flush();
String str = stdIn.readLine();
StringTokenizer tokenizer = new StringTokenizer(str, DELIM);
int k = tokenizer.countTokens();
if (k != 3) {
throw new Exception("Invalid input.");
}
name = tokenizer.nextToken();
String quantityFirst = tokenizer.nextToken();
String priceFirst = tokenizer.nextToken();
quantity = Integer.parseInt(quantityFirst);
price = Double.parseDouble(priceFirst);
if (quantity < 0) {
throw new Exception("Invalid input. Quantity less than 0");
}
if (price < 0) {
throw new Exception("Invalid input. Price less than 0");
}
}
catch (NumberFormatException nfe) {
stdErr.println(nfe.toString());
readProduct();
}
catch (Exception e){
stdErr.println(e.getMessage());
readProduct();
}
return new Product(name, quantity, price);
}
}