58,453
社区成员
发帖
与我相关
我的任务
分享
import java.util.Scanner;
import java.util.StringTokenizer;
import java.io.IOException;
/**
* Created by IntelliJ IDEA.
* User: Administrator
* Date: 2011-9-24
* Time: 19:05:34
* To change this template use File | Settings | File Templates.
*/
public class Demo1 {
private Product readProduct() throws IOException {
final String DELIM = "_";
String name = "";
int quantity = 0;
double price = 0.0;
/* PLACE YOUR CODE HERE */
System.out.print("Product [Name_Quantity_Price] :");
try
{
String s=new Scanner(System.in).next();
String[] inputs=s.split(DELIM);
// StringTokenizer st=new StringTokenizer(s,DELIM,true);
//
name+=inputs[0];
quantity=Integer.parseInt(inputs[1]);
price=Double.parseDouble(inputs[2]);
}
catch(NumberFormatException e)
{
e.printStackTrace();
}
return new Product(name, quantity, price);
}
public static void main(String[] args)throws Exception{
System.out.println(new Demo1().readProduct());
}
}
class Product{
private String name;
private int quantity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
private double price;
public Product(){}
public Product(String name,int quantity,double price){
this.name=name;
this.quantity=quantity;
this.price=price;
}
@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", quantity=" + quantity +
", price=" + price +
'}';
}
}
private Product readProduct() throws Exception {
final String DELIM = "_";
String name = "";
int quantity = 0;
double price = 0.0;
/* PLACE YOUR CODE HERE */
System.out.print("Product [Name_Quantity_Price] :");
try {
String s=new Scanner(System.in).nextLine();
if (!s.matches(".*?_\\d+_\\d+([.]\\d+)?")) { //可以做个一个判断
thorws new Exception("the format of input data is error.");
}
StringTokenizer st=new StringTokenizer(s,DELIM,true);
name+=st.nextToken();
quantity=Integer.parseInt(st.nextToken());
price=Double.parseDouble(st.nextToken());
} catch(NumberFormatException e) {
e.printStackTrace();
thorw e; //把异常抛出,否则要自己return一个null什么的
}
return new Product(name, quantity, price); //要不然这里就不对了
}