gpt4 book ai didi

java - 需要帮助我的代码有错误

转载 作者:行者123 更新时间:2023-12-02 11:14:20 25 4
gpt4 key购买 nike

创建一个名为Date的类。 Make Date具有一个名为getMonthName的静态方法,该方法采用一个整数,然后返回相应月份名称的String表示形式。数字1-12将分别映射到1月至12月。如果传递的值超出1-12,则返回“无效月份”。
查看所需的输出。在Date上添加两个构造函数:一个构造函数使用月,日和年的整数;另一个构造函数使用字符串月,日和年的整数。添加一个toString方法,该方法返回日期的格式如下:月日,年

我的代码如下

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));

}
}

我得到的错误是

Exception in thread "main" java.lang.NullPointerException at Date.getMonthNumber(Date.java:32) at Date.(Date.java:47) at DateDemo.main(DateDemo.java:19)



并且“月份”不显示,仅显示日期和年份。请帮忙!!

最佳答案

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是一个常量

关于java - 需要帮助我的代码有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28824150/

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