项目描述
- 来自尚硅谷的java课程的项目一
- 项目目标:
- 模拟实现一个基于文本界面的《家庭记账软件》
- 掌握初步的编程技巧和调试技巧
- 主要涉及以下知识点:
- 1.变量的定义
- 2.基本数据类型的使用
- 3.循环语句
- 4.分支语句
- 5.方法声明、调用和返回值的接收
- 6.简单的屏幕输出格式控制
代码
工具类
import java.util.InputMismatchException;
import java.util.Scanner;
public class Utility {
private static Scanner s=new Scanner(System.in);
private static String readKeyBoard(int lim){
String strInput="";
strInput=s.nextLine();
while(true){
if(strInput.length()<1&&strInput.length()<lim){
System.out.println("输入错误,请重新输入:");
continue;
}
break;
}
return strInput;
}
public static char readMenuSelection(){
char MenuSelection=' ';
while(true){
MenuSelection=readKeyBoard(1).charAt(0);
if(MenuSelection!='1'&&MenuSelection!='2'&&MenuSelection!='3'&&MenuSelection!='4'){
System.out.println("输入非选项要求的数字,请重新输入:");
}else{
break;
}
}
return MenuSelection;
}
public static int readNumber(){
int money=0;
while(true){
try{
money=Integer.parseInt(readKeyBoard(4));
break;
}catch(InputMismatchException e){
System.out.println("输入的不是整数数字,需要重新输入:");
}
}
return money;
}
public static String readString(){
return readKeyBoard(8);
}
public static char readComfirmSelection(){
char selection=' ';
while(true){
selection=readKeyBoard(1).toUpperCase().charAt(0);
if(selection!='Y'&&selection!='N'){
System.out.println("输入非要求的同意或否定,需重新输入:");
}else{
return selection;
}
}
}
}
框架及功能
public class FamilyAccount {
public static void main(String[] args){
boolean isTrue=true;
int originalMoney=10000;
String detail="";
while(isTrue){
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 menuSelection=Utility.readMenuSelection();
switch(menuSelection){
case '1':{
System.out.println("------当前收支明细记录------");
System.out.println("收 支\t账户金额\t收支金额\t说 明");
System.out.println(detail);
System.out.println("---------------------------");
break;
}
case '2':{
System.out.print("本次收入金额:");
int money=Utility.readNumber();
System.out.print("本次收入说明:");
String info=Utility.readString();
originalMoney+=money;
detail+="收入\t"+originalMoney+"\t\t"+money+"\t\t"+info+"\n";
System.out.println("------登记完成------");
break;
}
case '3':{
System.out.println("本次支出金额:");
int pay;
while(true){
pay=Utility.readNumber();
int isNegative=originalMoney-pay;
if(isNegative<0){
System.out.println("没有足够的钱去支出,请重新输入支出金额:");
}else{
originalMoney=isNegative;
break;
}
}
System.out.print("本次支出说明");
String info=Utility.readString();
detail+="支出\t"+originalMoney+"\t\t"+pay+"\t\t"+info+"\n";
System.out.print("------登记完成------");
break;
}
case '4':{
System.out.println("确认是否退出(Y/N)");
if(Utility.readComfirmSelection()=='Y'){
isTrue=false;
}
}
}
}
}
}