0

我正在创建使用此类来检索当前日期的程序。为了解决这个问题,我需要回到过去的一段时间。例如,今天是 3.11.2013 用户选择 18 个月期间,所以我使用此代码:

Calendar ca =Calendar.getInstance();
ca.add(Calendar.MONTH, -n);

其中 n 变量代表用户输入(月)。效果很好。但现在我想每月检索并在屏幕上显示如下:

September,2012
October,2012
.....
.....
November, 2013

我试图创建循环,但我不明白如何才能真正为每个循环运行添加 1 个月到开始日期。更新:

int i =0;
    Calendar ca =Calendar.getInstance();//iegūstam pašreizējo laiku
    ca.add(Calendar.MONTH, -n);
    ca.set(Calendar.DAY_OF_MONTH, 1);

while (i<n)
        {


            int month_n = ca.get(Calendar.MONTH);   
            int year_n = ca.get(Calendar.YEAR);

            try {//iegūstam datus ko rakstīt failā
                //record.setDate(5);//uzstādam vērtības
                record.setIncome(input.nextDouble());
                record.setAtv(atv_sum);
                record.setSumAtv(atv_sum+45.00);
                double iedz=(((record.getIncome()-record.getSumAtv())/100)*24);//iedz ienakuma nodoklis
                double soc_apd=(((record.getIncome()-record.getSumAtv())/100)*11);//sociālās apdr.nodoklis
                double netto =record.getIncome()-(iedz+soc_apd);

            if(record.getIncome()>0){
                    output.format("%-10s%-20s%-20s%-20s%-20s%-20s%-20s%-20s\n",
                                year_n,
                                month_n,
                                record.getIncome(),
                                record.getAtv(),
                                record.getSumAtv(),
                                iedz,soc_apd,netto);//null pointer exception
                                     }
            else
            {
                System.out.println("Kļūda alga ievadīta zem 0");
                input.nextLine();
            }           
            }
            catch ( FormatterClosedException formatterClosedException ){
                System.err.println("Kļūda rakstot failā");
                return;
            }
            catch (NoSuchElementException elementException){
                System.err.println("Nepareizs ievads. Mēģiniet vēlreiz");
                input.nextLine();
            }
        //  System.out.printf("%s  \n", "Ievadiet mēneša ienākumus ");
            ca.add(Calendar.MONTH, 1);
                i++;

        }

谢谢 :)

4

1 回答 1

2
Calendar ca = Calendar.getInstance(); // this is NOW

// set the date to the first of the month, to avoid surprises if the current date is 31.
ca.set(Calendar.DAY_OF_MONTH, 1);

// go n months before the first of this month
ca.add(Calendar.MONTH, -n);

for (int i = 0; i < n; i++) {
    // todo: format the date as you want and print it. See SimpleDateFormat

    // go to the next month
    ca.add(Calendar.MONTH, 1);
}
于 2013-11-03T14:51:49.790 回答