我正在创建使用此类检索当前日期的程序。为了解决这个问题,我需要回过头来。例如,今天是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++;
}
谢谢:)
答案 0 :(得分: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);
}