2011-05-07 60 views
0

我前段時間爲我的項目編寫了這個代碼,它應該計算用戶可能實現他的飲食目標的目標日期。但在測試應用程序時,我發現無論目標進入目標日期爲止,總是比創建日期多一個月。這個目標日期計算器出了什麼問題?

這是代碼

public String calcTD(SQLiteDatabase db){ 
    String date = null; 
    myDataBase = db; 
    Cursor c = myDataBase.rawQuery("SELECT * FROM USER", null); 
    if (c!= null){ 
     if (c.moveToFirst()){ 
      String cdate = c.getString(c.getColumnIndex("CreatedDate"));    
      String type = c.getString(c.getColumnIndex("GoalType"));    
      if (type == "Maintain Weight") 
       date = cdate; 
      else{    
      int rate = c.getInt(c.getColumnIndex("Rate")); 
      float gw = c.getFloat(c.getColumnIndex("GoalWeight")); 
      float cw = getCW(db); //get current weight 
      float w = 0; int days = 0; 
      if (type == "Lose Weight") 
       w = cw - gw; 
      else if (type == "Gain Weight") 
       w = gw - cw;     
      switch (rate){ 
      case 0: // the rate 250g/week 
       days = Math.round(w * 7 * 4); 
       break; 
      case 1: //the rate 500g/week 
       days = Math.round(w * 7 * 2); 
       break; 
      case 2://the rate 750g/week 
       days = Math.round(w * 7 * (4/3)) ; 
       break; 
      case 3:the rate 1kg/week 
       days = Math.round(w * 7); 
       break; 
      } 
      int y, m, d; 
          // the currentDate format (YYYYMMDD) 
      y = Integer.parseInt(cdate.substring(0,4)); 
      m = Integer.parseInt(cdate.substring(4,6)); 
      d = Integer.parseInt(cdate.substring(6,8));    
      GregorianCalendar i = new GregorianCalendar(y, m, d); 
      i.add(Calendar.DAY_OF_MONTH, days); 
      date = AllCmnMtd.getDate(i); // this will convert the date to a string with format (yyyymmdd)    

      }    
     } 
    } 
    return date;  
} 

對不起,我是這樣討厭的人,但兩個星期內我的項目的防守,而我面臨着許多錯誤,而測試的應用程序! :(。

謝謝你和問候

回答

3

Java的Calendar類使用基於0的索引數月。例0是一月和11月。

減去一個給M你把日曆前對象

+0

打我吧:) – Squonk 2011-05-07 21:38:56

+0

@MisterSquonk當我在一週前遇到同樣的bug時幫助我:-) – debracey 2011-05-07 21:41:21

+0

謝謝你爲我吸引注意:),我也有不計算事物的問題,但我通過改變比較字符串的方法來解決它(等於),現在每件事情都在工作!:) – Heba 2011-05-10 07:40:56