用java实现某公司预计明年有A, B, C, D四个新建项目,每个项目的投资额Ik及其投资后的收益Ek如下表所示,假设投资总额为3000万元,请问如何选择项目可以使总收益最大?
时间: 2024-05-08 11:15:25 浏览: 65
首先,我们需要计算每个项目的投资回报率ROI(Return on Investment),ROI=(投资后的收益-投资额)/投资额。然后按照ROI从高到低排序,选择ROI最高的项目进行投资,直到总投资额达到3000万元为止。
具体实现可以采用以下步骤:
1. 定义一个Project类,包含项目名称、投资额、投资后收益、ROI等属性和相应的getter和setter方法。
2. 创建四个项目对象,并设置它们的属性值。
3. 计算每个项目的ROI,并将所有项目按照ROI从高到低排序。可以使用Collections.sort()方法和Comparator接口来实现。
4. 根据排序后的项目列表,依次选择ROI最高的项目进行投资,直到总投资额达到3000万元为止。
5. 输出选择的项目名称和总收益。
以下是示例代码:
```
import java.util.*;
public class Project {
private String name;
private double investment;
private double profit;
private double roi;
public Project(String name, double investment, double profit) {
this.name = name;
this.investment = investment;
this.profit = profit;
this.roi = (profit - investment) / investment;
}
public String getName() {
return name;
}
public double getInvestment() {
return investment;
}
public double getProfit() {
return profit;
}
public double getROI() {
return roi;
}
public void setROI(double roi) {
this.roi = roi;
}
}
public class Investment {
public static void main(String[] args) {
Project[] projects = new Project[4];
projects[0] = new Project("A", 800, 1200);
projects[1] = new Project("B", 600, 1000);
projects[2] = new Project("C", 1000, 1500);
projects[3] = new Project("D", 600, 800);
Arrays.sort(projects, new Comparator<Project>() {
public int compare(Project p1, Project p2) {
if (p1.getROI() > p2.getROI()) {
return -1;
} else if (p1.getROI() < p2.getROI()) {
return 1;
} else {
return 0;
}
}
});
double totalInvestment = 0;
double totalProfit = 0;
for (Project project : projects) {
if (totalInvestment + project.getInvestment() <= 3000) {
totalInvestment += project.getInvestment();
totalProfit += project.getProfit();
System.out.println("Invested in project " + project.getName() + ", profit: " + project.getProfit());
}
}
System.out.println("Total investment: " + totalInvestment);
System.out.println("Total profit: " + totalProfit);
}
}
```
阅读全文