我有课程日期,只是简单地创建一周中几天的数组列表。
import java.util.*;
public class Date {
public static final String[] daysofTheWeek = {"Mon" , "Tue" , "Wed" , "Thurs" , "Fri" , "Sat" , "Sun"};
private String dayofweek;
private int day;
private int month;
public int getDate() {
return this.day;
}
public int getMonth() {
return this.month;
}
public Date(String dayofweek, int day, int month) {
this.day = 1;
if (day >= 1 && day <= 31) {
this.day = day;
}
this.month = 12;
if (month >= 1 && month <= 12) {
this.month = month;
}
this.dayofweek = "Mon";
if (isValidDOW(dayofweek)) { // why is this in the parameters?
this.dayofweek = dayofweek;
}
}
// must validate is DOW
// TRUE/FALSE is the day of the week matching?
public boolean isValidDOW(String d) {
for (int i = 0; i < dayofweek.length(); i++)
if (d.equals(daysofTheWeek[i])) { // why i?
return true;
}
return false;
}
// to string
public static String monthToString(int i) {
switch(i) {
case 1: return "January";
case 2: return "Feb";
case 3: return "March";
case 4: return "April";
case 5: return "May";
case 6: return "June";
case 7: return "July";
case 8: return "August";
case 9: return "September";
case 10: return "October";
case 11: return "November";
case 12: return "December";
default: return "Invalid Month!!";
}
}
public String toString() {
return this.dayofweek + "," + Date.monthToString(this.month) + " " + this.day;
}
public String getDayOfWeek() {
return this.dayofweek;
}
}
现在我正在努力争取所有的日子(比如,返回弹出的次数)。我尝试使用循环来计算所有内容,但我得到一个空指针异常。我一直在看这个问题,并且无法弄清楚它有什么问题。任何人都可以指导我朝正确的方向发展吗?
import java.util.*;
/**
* ArrayList example
*/
public class Calendar {
private ArrayList<Date> Schedule;
public ArrayList<Date> sundays(String dayofweek) {
ArrayList<Date> app = new ArrayList<Date>();
for (Date entry : Schedule) {
String d = entry.getDayOfWeek();
if (entry.getDayOfWeek() == dayofweek) {
app.add(entry);
}
else if (app.size() == 0) {
return null;
}
}
return app;
}
}
答案 0 :(得分:0)
您永远不会初始化字段Schedule
,因此默认初始化为null
。因此,行for (Date entry:Schedule)
(用于调用Schedule.iterator()
的语法糖并迭代生成的迭代器)会抛出NullPointerException
。
此外 - Java中的非静态字段名称应以小写字母开头。您应该将Schedule
更改为schedule
。 (或者您可以遵循其中一个更具体的命名约定。有些项目使用f
启动所有字段名称 - 在您的情况下fSchedule
;其他项目使用{{启动所有字段名称1}} for&#34; member&#34; - 在您的情况下,m
。如果您采用其中一种惯例,请务必保持一致。)
答案 1 :(得分:0)
我认为方法isValidDOW应该是:
public boolean isValidDOW(String d){
for (int i=0; i < daysofTheWeek.length; i++)
if ( d.equals(daysofTheWeek[i])) // why i?
{
return true;
}
return false;
}
使用 daysofTheWeek.length 而不是 dayofweek.length(),例如,如果dayofweek =&#39; Sat&#39;,for循环将只执行<强> 3 次,但周六&#39;在ArrayList daysofTheWeek中排在第6位,值 5 。