当前位置 : 主页 > 编程语言 > java >

用java分别列出物品的价格

来源:互联网 收集:自由互联 发布时间:2021-06-28
Example8_12 package wjw;import java.util.*;public class Example8_12 {public static void main(String[] args) {String shoppingReceipt="牛奶:8.5元,香蕉:3.6元,酱油:2.8元";PriceToken lookPriceMess=new PriceToken();System.out.print
Example8_12
package wjw;
import java.util.*;
public class Example8_12 {
	public static void main(String[] args) {
		String shoppingReceipt="牛奶:8.5元,香蕉:3.6元,酱油:2.8元";
		PriceToken lookPriceMess=new PriceToken();
		System.out.println(shoppingReceipt);
		double sum=lookPriceMess.getPriceSum(shoppingReceipt);
		System.out.printf("购物总价格%-7.2f",sum);
		int amount=lookPriceMess.getGoodsAmount(shoppingReceipt);
		double aver=lookPriceMess.getAverPrice(shoppingReceipt);
		System.out.printf("\n商品数目:%d,平均价格:%-7.2f",amount,aver);
			
	}

}
import java.util.*;
public class PriceToken {
	public double getPriceSum(String shoppingReceipt){
		String regex="[^0123456789.]+";
		shoppingReceipt = shoppingReceipt.replaceAll(regex, "#");
		StringTokenizer fenxi=new StringTokenizer(shoppingReceipt,"#");
		double sum=0;
		while(fenxi.hasMoreTokens()){
			String item=fenxi.nextToken();
			double price=Double.parseDouble(item);
			sum=sum+price;
		}
		return sum;
	}
	public double getAverPrice(String shoppingReceipt){
		double priceSum=getPriceSum(shoppingReceipt);
		int goodsAmount=getGoodsAmount(shoppingReceipt);
		return priceSum/goodsAmount;
	}
	public int getGoodsAmount(String shoppingReceipt){
		String regex="[^0123456789.]+";
		shoppingReceipt=shoppingReceipt.replaceAll(regex, "#");
		StringTokenizer fenxi=new StringTokenizer(shoppingReceipt,"#");
		int amount=fenxi.countTokens();
		return amount;
	}
}
网友评论