import java.util.Locale;
import java.util.Scanner;
public class FamilyAccount {
public static void main(String[] args) {
Utility t = new Utility();
int balance = 10000;
boolean isFlag = true;
String details = "收支\t账户金额\t收支金额\t说 明\n";
while (isFlag) {
System.out.println("---------欢迎使用家庭收支系统---------");
System.out.println("1 收支明细");
System.out.println("2 登记收入");
System.out.println("3 登记支出");
System.out.println("4 退 出");
System.out.println("--------------------------------------\n");
System.out.println("请输如您的选项:");
char selectionMenu = t.readMenuSelection();
switch (selectionMenu) {
case '1':
System.out.println(details);
break;
case '2':
System.out.println("请输入收入金额:");
int money = t.readNumber();
System.out.println("请输入收入说明:");
String addInfo = t.readInfo();
//更新余额
balance += money;
details += ("收入" + "\t" + balance + "\t" + money + "\t\t" + addInfo + "\n");
System.out.println("------------------登记收入成功-----------------------\n");
break;
case '3':
System.out.println("请输入支出金额:");
int outMoney = t.readNumber();
System.out.println("请输入支出说明:");
String outInfo = t.readInfo();
//更新余额
balance -= outMoney;
details += ("收入" + "\t" + balance + "\t" + outMoney + "\t\t" + outInfo + "\n");
System.out.println("------------------登记支出成功-----------------------\n");
break;
case '4':
System.out.println("是否确认退出? (Y or N)");
boolean confirmChoose = t.isConfirmChoose();
if ( confirmChoose == true ) {
isFlag = false;
}
break;
}
}
}
}
class Utility {
public static Scanner sc = new Scanner(System.in);
//从键盘读入长度不超过limit的字符串
private static String readKeyBorad(int limit) {
while (true) {
String str = sc.nextLine();
if ( str.length() < 1 || str.length() > limit) {
System.out.println("输入错误,(长度不能超过" + limit + ")请重新输入:");
continue;
} else {
return str;
}
}
}
//从键盘读入收支金额
public static int readNumber() {
int tempMoney;
while (true) {
String money = readKeyBorad(5);
try {
//将字符串转换为数字
tempMoney = Integer.parseInt(money);
break; //try语句中一定要加break跳出循环
} catch (NumberFormatException e) { //捕捉字符串转换为数字的异常
System.out.println("数字输入异常,请重新输入:");
}
}
return tempMoney;
}
//从键盘读入菜单选项
public static char readMenuSelection() {
char c;
while (true) {
String str = readKeyBorad(1);
c = str.charAt(0); //获取字符串的第一个字符
if ( c != '1' && c != '2' && c != '3' && c != '4') {
System.out.println("选项输入错误,请重新输入:");
continue;
} else {
break;
}
}
return c;
}
//从键盘录入是否确认(Y/N)
public static boolean isConfirmChoose() {
boolean flag;
while (true) {
String str = readKeyBorad(1);
//字符串转为大写
String strUpper = str.toUpperCase(Locale.ROOT);
//获取字符串的第一个字符
char c = strUpper.charAt(0);
if ( c == 'Y') {
flag = true;
break;
} else if ( c == 'N') {
flag = false;
break;
} else {
System.out.println("输入错误,请重新输入:");
continue;
}
}
return flag;
}
//从键盘读入收支说明
public static String readInfo() {
String str = readKeyBorad(16);
return str;
}
}
简单家庭收支记账
于 2022-07-19 17:37:51 首次发布