Product.java

package javaDemo1;

/**
 * 商品实体类
 * 
 * @author Monster丶ZF @version1.8
 * @data 2019年5月6日
 * @remakeTODO
 */
public class Product {
	private String name;
	private double price;
	/** 商品的描述 */
	private String description;
	/** 商品的服务 */
	private String[] services;
	
	public  Product(){}
	
	public Product(String name, String description){
		setName(name);
		setDescription(description);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String[] getServices() {
		return services;
	}

	public void setServices(String[] services) {
		this.services = services;
	}

}

ProductBiz.java

package javaDemo1;

import javax.swing.JOptionPane;

/**
 * 商品管理类
 * @author Monster丶ZF
 * @version1.8
 * @data 2019年5月6日
 * @remakeTODO
 */
public class ProductBiz {
	public static void main(String[] args) {
		/**用来保存每种商品的总量*/
		int[] counts = new int[3];
		/**最终要支付的总金额*/
		double total = 0;
		//改进:使用对象数组
		Product[] products = new Product[3];
		for (int i = 0; i < counts.length; i++) {
//			/**局部变量,for循环结束后就没了*/
//			Product product = new Product();	
			products[i] = new Product();//对象数组使用之前一定要记得给他分配空间
			String name = JOptionPane.showInputDialog("请输入商品名称:");
			products[i].setName(name);
			//接收用户输入的商品单价,要注意,返回值是字符串类型!!
			String strPrice = JOptionPane.showInputDialog("请输入商品的单价:");
			//需要将字符串类型转换成double类型,在进行赋值
			//转换前最好验证正确性,以避免异常
			products[i].setPrice(Double.parseDouble(strPrice));
			String strCount = JOptionPane.showInputDialog("请输入购买的数量:");
			counts[i] = Integer.parseInt(strCount);
			
			//累加总金额
			total += products[i].getPrice() * counts[i];
		}
		System.out.println("购物结算:");
		for (int i = 0; i < products.length; i++) {
			System.out.println(products[i].getName() + "\t" +products[i].getPrice());
		}
		System.out.println("商品总金额为:" +  total);
	}
 
}

商品简单管理

相关文章: