package com.basic.study.realization.smallchange2;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
public class SmallChangeOop {
private boolean loop = true;//菜单循环 控制
private String details = "================零钱通收支情况================";//收支情况
private double money;//记录收入或者支出
private double balance;//余额
private final Scanner scanner = new Scanner(System.in);
private Date date;//时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//时间格式化
public void show() {
do {
System.out.println("================零钱通菜单================");
System.out.println("\t\t1 零钱通明细\n\t\t2 收益入账\n\t\t3 消费\n\t\t4 退出");
System.out.println("请选择(1 - 4 ):");
//菜单选择
String key = scanner.next();
switch (key) {
case "1":
details();//收支情况
break;
case "2":
income();//收入
break;
case "3":
consume();//消费
break;
case "4":
exit();//退出
break;
default:
System.out.println("输入有误!请输入1-4的数字");
}
} while (loop);
}
public void details() {
if (details.length() == 39) {//39为“===..零钱通收支情况====..的长度
System.out.println("您还没有任何消费或者收益信息");
} else {
System.out.println(details);
}
}
public void consume() {
boolean incomeLoop = true;
int count = 1;
do {
System.out.println("请输入消费金额:");
if (scanner.hasNextDouble()) {//判断输入是否为double
double temp = scanner.nextDouble();
if (temp < 0) {
System.out.println("输入金额有误!应该>0");
} else if (temp > balance) {
System.out.println("余额不足,消费失败!");
return;
} else {
scanner.nextLine();//清空缓存区,不然会无限循环
money = temp;
System.out.println("请输入你的消费类型:(长度应在10个字以内)");
String income = scanner.nextLine();
if (income.length() > 10) {//限制消费类型字数
System.out.println("输入错误,返回零钱通界面");
return;
}
balance -= money;
incomeLoop = false;
date = new Date();
details += "\n" + income + "\t\t-" + money + "\t\t时间\t\t" + sdf.format(date) + "\t\t余额\t\t" + balance;//拼接信息
}
} else {//错误次数设置
if (count == 3) {
System.out.println("输入错误次数已达三次,将返回零钱通界面!");
incomeLoop = false;
}
count++;
System.out.println("请输入数字!");
}
} while (incomeLoop);
}
public void income() {//类似代码看上面
boolean incomeLoop = true;
int count = 1;
do {
System.out.println("请输入收益金额:(单笔收入在20000以下)");
scanner.nextLine();
if (scanner.hasNextDouble()) {
double temp = scanner.nextDouble();
if (temp < 0 || temp > 20000) {
System.out.println("输入金额有误!返回零钱通界面");
scanner.nextLine();
return;
} else {
money = temp;
balance += money;
incomeLoop = false;
date = new Date();
details += "\n收益入账\t\t+" + money + "\t\t时间\t\t" + sdf.format(date) + "\t\t余额\t\t" + balance;
}
} else {
if (count == 3) {
System.out.println("输入错误次数已达三次,将返回零钱通界面!");
incomeLoop = false;
}
count++;
System.out.println("请输入数字!");
}
} while (incomeLoop);
}
public void exit() {
scanner.nextLine();
System.out.println("请确认是否退出 y or n");
String answer = scanner.nextLine();
if (answer.equals("Y") || answer.equals("y")) {
loop = false;
}
}
}
Java零钱通小游戏的实现
需积分: 0 19 浏览量
2024-03-15
20:48:52
上传
评论
收藏 2KB ZIP 举报
想做大学士
- 粉丝: 41
- 资源: 4