创建一个名为Date的类。 Make Date有一个名为getMonthName的静态方法,它接受一个整数,然后返回相应月份名称的String表示。数字1-12将分别映射到1月至12月。如果超过1-12的值,则返回"无效的月份"。 查看所需的输出。向Date添加两个构造函数:一个采用整数月,日和年的另一个构造函数,其中需要一个字符串月,以及整数日和年。添加toString方法,返回日期格式如下:Month Day,Year
我的代码如下
public class Date
{
private static String[] monName;
private int month, day, year;
public static String getMonthName(int num)
{
if(num < 1 || num > 12)
{
return "invalid month";
}
else
{
String[] name = {" ", "January", "February", "March", "April", "May"
, "June", "July", "August", "September", "October","November", "December"};
return name[num];
}
}
public static int getMonthNumber(String monthName)
{
for(int n = 1; n <= 12; n++)
{
if (monthName.equalsIgnoreCase(monName[n]))
return n;
}
return -1;
}
public Date(int month, int day, int year)
{
this.month = month;
this.day = day;
this.year = year;
}
public Date (String month, int day, int year)
{
this(day, getMonthNumber(month), year);
}
public String toString()
{
String m = month + day + ", " + year;
return m;
}
}
运行我的代码的测试代码是
import java.util.Random;
public class DateDemo
{
public static void main(String[] args)
{
System.out.println("-- Number Tests --");
Random r = new Random(0);
for (int x = 0; x < 50; x++)
{
Date d = new Date(Math.abs(r.nextInt() % 12) + 1, //month
Math.abs(r.nextInt()) % 28, //day
1900 + r.nextInt() % 100); //year
System.out.println(d);
}
System.out.println("-- Month Name Tests --");
System.out.println(new Date("January", 1, 1970));
System.out.println(new Date("February", 1, 1970));
System.out.println(new Date("March", 1, 1970));
System.out.println(new Date("April", 1, 1970));
System.out.println(new Date("May", 1, 1970));
System.out.println(new Date("June", 1, 1970));
System.out.println(new Date("July", 1, 1970));
System.out.println(new Date("August", 1, 1970));
System.out.println(new Date("September", 1, 1970));
System.out.println(new Date("October", 1, 1970));
System.out.println(new Date("November", 1, 1970));
System.out.println(new Date("December", 1, 1970));
}
}
我得到的错误是
线程中的异常&#34; main&#34;显示java.lang.NullPointerException at Date.getMonthNumber(Date.java:32) 在日期。(Date.java:47) 在DateDemo.main(DateDemo.java:19)
并且月份不显示,仅显示日期和年份。请帮助!!
答案 0 :(得分:1)
private static String[] monName;
永远不会分配值,因此,它是null
我“想”你想从String[] name = {" ", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October","November", "December"};
方法中取出getMonthName
并转而转到monName
而不是......
private static final String[] MONTH_NAMES = String[] name = {
" ",
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"};
是的,您必须重命名monName
,因为人们会将MONTH_NAMES
视为常量