这是一个关于账本记录的程序,其中实现了收入和支出记录以及每笔收支的明细,主要用到的知识包括分支与循环。在这个程序里,我学会了将各个功能模块化,从而使得程序更加清晰。该程序包括2个java文件,一个是Utility.java文件,该文件实现了判断从键盘读取数据是否正确。如下:
package hello;
import java.util.Scanner;
public class Utility {
private static Scanner scanner=new Scanner(System.in);
public static char readMenu() {
char c;
for(;;) {
String str=readKeyBoard(1);
c=str.charAt(0);
if(c!='1'&&c!='2'&&c!='3'&&c!='4') {
System.out.println("输入有误,请重新输入:");
}else {
break;
}
}
return c;
}
public static String readString() {
String str=readKeyBoard(8);
return str;
}
public static int readNumber() {
int n;
for(;;) {
String str=readKeyBoard(4);
try {
n=Integer.parseInt(str);
break;
} catch (NumberFormatException e) {
// TODO: handle exception
System.out.println("数字输入错误,请重新输入!");
}
}
return n;
}
public static char readConfirm() {
char c;
for(;;) {
String str=readKeyBoard(1).toUpperCase();
c=str.charAt(0);
if(c=='Y'||c=='N') {
break;
}
else {
System.out.println("选择错误,请重新输入!");
}
}
return c;
}
private static String readKeyBoard(int limit) {
String line="";
while(scanner.hasNext()) {
line=scanner.nextLine();
if(line.length()<1||line.length()>limit) {
System.out.println("输入长度(不大于"+limit+")错误,请重新输入");
continue;
}
break;
}
return line;
}
}
接下来就是project1.java文件,该文件实现了明细记录、收支登记以及退出系统的功能,代码如下:
package hello;
public class project1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean isFlag=true;
//用于记录用户收支的详情
String detail="收支\t账户金额\t收支金额\t说 明";
int balance=10000;
while (isFlag) {
System.out.println("------------家庭收支记账软件------------\n");
System.out.println(" 1 收支明细");
System.out.println(" 2 登记收入");
System.out.println(" 3 登记支出");
System.out.println(" 4 退 出");
System.out.println();
System.out.print(" 请选择<1-4>:");
char selection=Utility.readMenu();
switch(selection) {
case '1': System.out.println("--------当前收支明细记录---------");
System.out.println(detail);
break;
case '2': System.out.print("本次收入金额:");
int money=Utility.readNumber();
System.out.print("本次收入说明:");
String info=Utility.readString();
balance+=money;
//处理detail
detail+=("\n收入\t"+balance+"\t"+money+"\t"+info);
System.out.println("---------登记完成----------");
break;
case '3': System.out.print("本次支出金额:");
int output=Utility.readNumber();
System.out.print("本次支出说明:");
String info1=Utility.readString();
if(balance>=output) {
balance-=output;
detail+="\n支出\t"+balance+"\t"+output+"\t"+info1;
System.out.println("---------登记完成----------");
break;
}else {
System.out.println("支出超出额度,支付失败");
break;
}
case '4': //System.out.println("4.退 出");
System.out.print("确认是否退出(Y/N)");
char isExit=Utility.readConfirm();
if(isExit=='Y') {
isFlag=false;
}
}
}
}
}