一、项目描述
家庭记账软件,记录家庭收支情况。初学java项目
二、项目功能
1.账目记录
2.收入情况
3.支出情况
4.退出
三、项目讲解
四、业务代码
1.引用封装类:Utility
import java.util.Scanner;
public class Utility{
private static Scanner scanner = new Scanner(System.in);
/**
* 用户菜单1-4的选择
* charAt() 方法用于返回指定索引处的字符。索引范围为从 0 到 length() - 1。
* */
public static char readMenuSelection()
{
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;
}
/**
* 用于收入和支出的金额设置,最大不超过4位数
* */
public static int readNumber()
{
int n;
for( ; ; ){
String str = readKeyBoard(4);
try {
n = Integer.parseInt(str);
break;
}catch (NumberFormatException e) {
System.out.println("数字输入错误,请重新输入:");
}
}
return n;
}
/**
* 描述收入和支出的说明情况
* */
public static String readString()
{
String str = readKeyBoard(8);
return str;
}
public static char readConfirmSelection()
{
char c;
for ( ; ; ){
String str = readKeyBoard(1).toUpperCase();
c = str.charAt(0);
if (c == 'Y' || c == 'n'){
break;
} else {
System.out.print("选择错误,请重新输入:");
}
}
return c;
}
/**
* nextLine 将此扫描仪推进到当前行并返回跳过的输入。
* */
private static String readKeyBoard(int limit)
{
String line = "";
while (scanner.hasNext()) {
line = scanner.nextLine();
if (line.length() < 1 || line.length() > limit) {
System.out.print("输入长度(不大于" + limit + ")错误,请重新输入:");
continue;
}
break;
}
return line;
}
}
2.前端调用类:FamilyAccount
class FamilyAccount
{
/**
* 问题1:说明乱码???形式展示
* */
public static void main(String[] args)
{
double balance = 10000.0; // 初始金额
boolean flag = true; // 循环标志
String info = ""; // 记录信息
while(flag)
{
System.out.println("-----------------家庭收支记账软件-----------------");
System.out.println();
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 mode = Utility.readMenuSelection();
System.out.println();
switch (mode)
{
//记录
case '1':
System.out.println("\n-----------------当前收支明细记录-----------------");
System.out.println("收支\t账户金额\t收支明细\t说明");
if (info == ""){
System.out.println("请先记账");
break;
}
System.out.println(info);
System.out.println("写入完成");
break;
//收入
case '2':
System.out.print("本次收入金额:");
double in_moeny = Utility.readNumber();
System.out.print("本次收入说明:");
balance += in_moeny;
String in_info = Utility.readString();
info += "收入\t" + balance + " \t+" + in_moeny + "\t \t" + in_info + "\n";
break;
//支出
case '3':
System.out.print("本次支出金额:");
double out_moeny = Utility.readNumber();
System.out.print("本次支出说明:");
balance -= out_moeny;
String out_info = Utility.readString();
info += "支出\t" + balance + " \t-" + out_moeny + "\t \t" + out_info + "\n";
break;
//退出
case '4':
System.out.println("确认是否退出(Y/N):");
char isExit = Utility.readConfirmSelection();
if(isExit == 'Y'){
flag = false;
}
break;
}
}
}
}
3.项目展示图片: