gpt4 book ai didi

月份对象的 Java 类

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

我正在为 Month 对象开发一个 Java 类,但它没有返回实际的月份,你能帮忙吗?

这是私有(private)方法类:

public class Month
{
private static int numInstantiated = 0;
private int monthNumber = 0;

public Month()
{
monthNumber = 1;
numInstantiated++;
}
public Month(int num)
{
monthNumber = num;
numInstantiated++;
}

public void setMonth(int newMonth)
{
monthNumber = newMonth;
}
public int getMonth()
{
return monthNumber;
}

public String toString()
{
switch(monthNumber)
{
case 1: return "January";
case 2: return "February";
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 "No month specified";
}
}

}

这是主要内容:

import java.util.Scanner;

public class UseMonth
{
public static void main(String[] args)
{
Scanner kbd = new Scanner(System.in);
Month m1 = new Month();
Integer newMonth;

//kbd.nextLine();
System.out.print("Please enter a numeric representaion of the Month? (ex. 1 for January)");
newMonth = kbd.nextInt();
m1.setMonth(newMonth);

System.out.println("You entered: " + newMonth + ", which is the month of " + m1.getMonth());
}
}

提前致谢 - 弗雷德

最佳答案

好吧,您正在调用返回 int 的 getMonth() 。您需要调用 m1.toString(),它返回您尝试打印的字符串表示形式。

关于月份对象的 Java 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20332850/

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