gpt4 book ai didi

java - 以日期为键的多维数组

转载 作者:行者123 更新时间:2023-12-01 15:36:26 25 4
gpt4 key购买 nike

public void buildArrayForMonth(int month, int year, int numOfDays, JSONArray array){
JSONObject[][] monthArray = null;

SimpleDateFormat monthFormat = new SimpleDateFormat("M");
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat dateFormat = new SimpleDateFormat("d");

for(int i=0;i<array.length();i++){

try {
JSONObject event = array.getJSONObject(i);
String date_full = event.getString("date_full");

Date date = new Date(HttpDateParser.parse(date_full));
int theMonth = Integer.parseInt(monthFormat.format(date)) - 1;
int theYear = Integer.parseInt(yearFormat.format(date));
int theDate = Integer.parseInt(dateFormat.format(date));

if(theMonth == month && theYear == year){
System.out.println("This Month" + date_full);
monthArray[theDate][monthArray[theDate].length] = event; //add event object to the month array and its respective date

}


} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}



}

我本质上希望日期是一个包含 JSONObjects 的数组。我的应用程序因我现在拥有的内容而崩溃。我不确定你是否能做到这一点。 Java有push或者add之类的东西吗?

最佳答案

您忘记在初始化之前创建一个数组(我认为您在示例代码中遇到了 NullPointerException):

monthArray = new JSONObject[32][32];

此外,HashMap 对于该任务可能更有用。

UPD 操作,还有一个问题,为什么需要二维数组?我认为一维就足够了。

JSONObject monthArray = new JSONObject[32];
monthArray[theDate] = event

UPD2 我建议使用 Calendar而不是日期和 SimpleDateFormat。这是更正确的方法,例如:

Calendar c = Calendar.getCalendar();
c.setTimeInMillis(HttpDateParser.parse(date_full));
int theMonth = c.get(Calendar.MONTH);
int theYear = c.get(Calendar.YEAR);
int theDate = c.get(Calendar.DAY_OF_MONTH);

UPD3

评论后更新。如果一天内可能发生多个事件,那么您可以按照我的建议使用 HashMap 和 List。

HashMap<Integer, List<JSONObject>> monthArray = new HashMap<Integer, List>();
...
if (...) {
...
List l = monthArray.get(theDate);
if (l == null) {
l = new LinkedList<JSONObject>();
}

l.add(event);

monthArray.put(theDate, l);
}

关于java - 以日期为键的多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8772977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com