参考上一篇,项目在主方法中运行的弊端,不易修改,也不能随用随调,结合面向对象的优势,因此有了以下代码的实现:分两个部分,一个类是完成零钱通的各个功能,另一个类用于调用该类的方法。
代码如下(功能类展示):
/*
该类是完成零钱通的各个功能的类
*/
public class OOP {
boolean loop = true;
double money = 0;//入账金额
double balance = 0;//余额
double cost = 0;//消费
String name;//消费名称
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh: mm");
String details = "----------零钱通明细---------";
Scanner scan = new Scanner(System.in);
//第一个模块显示菜单
void showMain() {
do {
System.out.println("----------零钱通菜单---------");
System.out.println("\t\t\t\t1.零钱通明细\t\t\t\t");
System.out.println("\t\t\t\t2.收益入账\t\t\t\t");
System.out.println("\t\t\t\t3.消费\t\t\t\t");
System.out.println("\t\t\t\t4.退 出\t\t\t\t");
System.out.println("请选择(1-4):");
int key = scan.nextInt();
switch (key) {
case 1:
this.getDetails();
break;
case 2:
this.income();
break;
case 3:
this.pay();
break;
case 4:
this.exit();
break;
default:
System.out.println("输入有误,请重新输入");
}
} while (loop);
System.out.println("退出零钱通");
}
//显示明细
public void getDetails() {
System.out.println(details + "\n");
}
//收入
void income() {
do {
System.out.println("请输入入账金额");
money = scan.nextDouble();
if (money > 0) {
balance += money;
} else {
System.out.println("money输入有误,请重新输入:");
}
} while (money < 0);
details += "\n" + "收益入账\t+" + money + "\t" + sdf.format(date) + "\t" + balance;
}
void pay(){
System.out.println("请输入消费名称:");
name = scan.next();
do {
System.out.println("请输入消费金额:");
cost = scan.nextDouble();
if (cost > 0) {
balance -= cost;
} else {
System.out.println("cost输入有误,请重新输入:");
}
} while (cost < 0);
details += "\n-" + name + "\t" + cost + "\t" + sdf.format(date) + "\t" + balance;
}
void exit(){
System.out.println("你确定要退出吗?y/n");
char ans = scan.next().charAt(0);
if (ans == 'y') {
loop = false;
} else if (ans == 'n') {
System.out.println("请重新选择(1-4):");
} else System.out.println("输入有误,请重新输入:(y/n)");
}
}
第二个类举例:
public class App {
public static void main(String[] args) {
new OOP().showMain();
}
}