1020月饼java答案和出错点

这道题有几个点需要注意:
1.除了月饼总类和市场总需求量题目指明是正整数以外,剩下的题目都说的是正数,所以需要在定义月饼类的私有变量的时候设置位为double
2.因为这道题的月饼总类在不超过1000的范围内,所以不适合使用Scanner,应该使用bufferedReader;并且对于定义的月饼类可以让它实现comparable的接口,这样就可以使用java的list集合自带的排序,这一条主要是为了解决运行超时的问题

下面是这道题的java代码答案:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{
  public static void main(String[] args) throws IOException{
	  BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(System.in));
	  String[] values=new String[2];
	  values=bufferedReader.readLine().split(" ");
	  int times=Integer.parseInt(values[0]);//月饼种类
	  int demands=Integer.parseInt(values[1]);//市场总需求量
	  if (times <= 0 || times > 1000 || demands <= 0 || demands > 500)
          return;
	  double maxProfit=0;//最大利润
	  List<MoonCake> moonCakes=new ArrayList<MoonCake>();
	  String[] inventories=new String[times];//月饼库存集合
	  String[] totalPrices=new String[times];//月饼总价
	  inventories=bufferedReader.readLine().split(" ");
	  totalPrices=bufferedReader.readLine().split(" ");
	  bufferedReader.close();
//	  对月饼库存量赋值
	  for(int i=0;i<times;i++) {
		  MoonCake moonCake=new MoonCake();
		  moonCake.setInventory(Double.parseDouble(inventories[i]));
		  moonCake.setTotalPrice(Double.parseDouble(totalPrices[i]));
		  moonCake.setPrice();
		  moonCakes.add(moonCake);
	  }
//	  对月饼数组排序
	  Collections.sort(moonCakes);
//	  按照单价从高到低对市场需求量分配月饼
	  for(int i=0;i<times;i++) {
		  if(demands-moonCakes.get(i).getInventory()>=0) {
			  maxProfit+=moonCakes.get(i).getTotalPrice();
			  demands-=moonCakes.get(i).getInventory();
		  }else {
			  maxProfit+=moonCakes.get(i).getPrice()*demands;
			  break;
		  }
	  }
	  System.out.format("%.2f",maxProfit);
  }
}

class MoonCake implements Comparable<MoonCake>{
	private double inventory;//库存
	private double totalPrice;//总售价
	private double price;//单价
	public double getInventory() {
		return inventory;
	}
	public void setInventory(double inventory) {
		this.inventory = inventory;
	}
	public double getTotalPrice() {
		return totalPrice;
	}
	public void setTotalPrice(double totalPrice) {
		this.totalPrice = totalPrice;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public void setPrice() {
		this.price = this.totalPrice/this.inventory;
	}
	@Override
	public int compareTo(MoonCake mooncake) {
		if(mooncake.price>this.price) {
			return 1;
		}else if(mooncake.price==this.price) {
			return 0;
		}else {
			return -1;
		}
	}
}
全部评论

相关推荐

10-11 15:42
皖西学院 Java
青鱼LINK:我硕士,也是java0面试,吾道不孤
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务