繁体   English   中英

在Java中使用对象(实体)

[英]Using objects in java (entities)

我是java的新手,我已经开发了一个程序,该程序允许用户输入其输入和结果,还可以看到两者的摘要(第二个代码示例)。

我使用文本文件存储数据(第一个示例)。 我为每个用户使用两个文本文件,一个用于收入,一个用于结果。

Bonus //category
21 //amount
28/12/2015 //date
Salary
13
03/01/2016
Savings Deposit
33
03/01/2016

以下代码示例总结了用户的信息和结果(注意:opnEsoda是扫描仪):

try {
while (opnEsoda.hasNextLine());

               do //I read only the lines with the amounts from textfile
                        {
                            String[] entry = new String[3];

                            int x =0;
                            for (int i = 0; i < 3; i++)
                            {
                                if (opnEksoda.hasNextLine())
                                {
                                    // Trim removes leading or trailing whitespace.
                                    entry[i] = opnEksoda.nextLine().trim();

                                }

                            }
                           x = Integer.parseInt(entry[1]); // converts string numbers to int
                           sumeksoda += x ; // addition ... Amounts of the txt file 
                        }

              while (opnEksoda.hasNextLine());
                // information dialog that show the money spent and got.
                    JOptionPane.showMessageDialog(null,
                    "You got: "+sumesoda+" €",
                    "Your stats",
                    JOptionPane.INFORMATION_MESSAGE,icon);


            } catch (FileNotFoundException e) {
                System.out.println("COULD NOT READ FILE!!!");
            }

它将打印:您有67€

我的目标是分发本周和本月花费的资金。 我也想知道在每个类别上花费的金额(可选)。 最好的方法是什么?

要计算当前月份的收入,您必须分析循环内的entry [2](日期),并且仅汇总那些月份相同的值。

在程序开始时,存储当前日期:

GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());                          // store the current date
int curYear  = cal.get(cal.YEAR );
int curMonth = cal.get(cal.MONTH);

然后,在读取文件时,解析日期并比较年份和月份:

cal.setTime(new SimpleDateFormat("dd/MM/yyyy").parse(entry[2]));   // parse the date
if( cal.get(cal.YEAR)==curYear && cal.get(cal.MONTH)==curMonth ){
    x = Integer.parseInt(entry[1]); // converts string numbers to int
    sumeksoda += x ; // addition ... Amounts of the txt file 
}

要计算每个类别的收入 ,必须分析entry [0](类别)。 如果预先知道类别,则只需创建几个不同的总和变量:

int sumeksodaSalary=0;
int sumeksodaBonus=0;

然后,在循环内:

if("Salary".equals(entry[0])) sumeksodaSalary += x ;
if("Bonus" .equals(entry[0])) sumeksodaBonus  += x ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM