import java.io.*;
import java.util.*;
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;
public static void main(String[] args) throws IOException {
ShoppingCartApplication application = new ShoppingCartApplication();
application.run();
}
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();
}
}
private int getChoice() throws IOException {
do {
int input;
try {
stdErr.println();
stdErr.print("[0] Quit/n"
+ "[1] Add Product/n"
+ "[2] Display Products/n"
+ "[3] Display Total/n"
+ "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);
}
private Product readProduct() throws IOException {
final String DELIM = "_";
String name = "";
int quantity = 0;
double price = 0.0;
/* PLACE YOUR CODE HERE */
boolean flag=true;
while(flag) { //进入输入的循环
stdErr.print("product [name_qty_price]> "); //提示输入
stdErr.flush();
String readLine = stdIn.readLine(); //读取输入
StringTokenizer st = new StringTokenizer(readLine, "_");
if(st.countTokens() == 3) {
try {
name = st.nextToken();
quantity = Integer.parseInt(st.nextToken());
price = Double.parseDouble(st.nextToken());
flag = false; //如果输入正确,flag=false,退出循环
}catch(NumberFormatException nfe) { //类型错误
stdErr.println("Invalid input");
flag = true; //进入新一轮循环,重新输入
}finally {
if(quantity <= 0 || price <= 0) { //数据不符合
stdErr.println("Invalid input");
flag = true; //进入新一轮循环,重新输入
}
}
}
else { //输入格式错误
stdErr.println("Invalid input");
flag = true;
}
}
return new Product(name, quantity, price); //成功读取数据
}
}
考察:
1.对java.util.StringTokenizer用法的掌握
2.对各类异常的处理