源代码如下:
model层
package zlc.model;
/***
* @author 信1705-1班赵路仓
* @version 1.0
*/
public class Data {
private double r; //贴现率
private double y; //贴现因子
private double rmb; //现金
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getRmb() {
return rmb;
}
public void setRmb(double rmb) {
this.rmb = rmb;
}
}
view层
package zlc.view;
/***
* @author 信1705-1班赵路仓
* @version 1.0
*/
public class View {
public void print(double sum) {
System.out.println(sum);
}
}
Controller层
package zlc.controller;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import zlc.model.Data;
import zlc.view.View;
/***
* @author 信1705-1班赵路仓
* @version 1.0
*/
public class Controller {
DecimalFormat format = new DecimalFormat("#.00");
Scanner sc = new Scanner(System.in);
private Data data;
private View view;
public Controller(Data data,View view) {
this.data=data;
this.view=view;
}
public static double formatDouble1(double d) {
return (double)Math.round(d*10000)/10000;
}
//键盘输入数据
public List<Data> Scin() {
List<Data> datas =new ArrayList<Data>();
try {
System.out.println("请输入年数:");
int x = sc.nextInt();
System.out.println("请输入贴现率:");
double y = sc.nextDouble();
for(int i=0;i<=x;i++) {
Data data=new Data();
System.out.println("请输入第"+i+"年的盈亏金额:");
double rmb = sc.nextDouble();
data.setR(y);//贴现率
data.setRmb(rmb);//本年金额
data.setY(1/Math.pow((1+y), i));//,第一年的贴现因子是rmb本身,所以无需讨论初始投资年的情况
System.out.println("第"+i+"年,"+"贴现率"+y+"贴现因子"+formatDouble1((1/Math.pow((1+y), i)))+"金额:"+rmb+"计算后"+rmb*formatDouble1((1/Math.pow((1+y), i))));
datas.add(data);
}
}catch(Exception e) {
System.out.println("输入格式错误!");
}
return datas;
}
//计算净现值
public double count() {
List<Data> datas =new ArrayList<Data>();
double sum = 0;
datas=Scin();
for(Data d:datas) {
sum+=formatDouble1(d.getRmb())*formatDouble1(d.getY());
//System.out.println(d.getRmb());
//System.out.println(d.getY());
//System.out.println(d.getRmb()*d.getY());
//System.out.println("净现值为:"+sum);
}
return sum;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public View getView() {
return view;
}
public void setView(View view) {
this.view = view;
}
}
Demo测试类
package demo;
import zlc.controller.Controller;
import zlc.model.Data;
import zlc.view.View;
public class Demo {
public static void main(String[] args) {
Data data=new Data();
View view=new View();
Controller controller=new Controller(data,view);
System.out.println("程序开始");
view.print(controller.count());
System.out.println("程序结束");
}
}
测试步骤: