月份对象的 Java 类

标签 java class

我正在为 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/

相关文章:

php - 如何在php中实现鸡鸡蛋鸟类接口(interface)问题

c++ - 如何在两个实例中使用值进行计算?

c++ - 是否有语法来防止类的实例是常量?

java - Bean Validation 验证一个验证是否有效?

java - 无法启动服务 jboss.persistenceunit : org. hibernate.service.UnknownServiceException

java - Tomcat 7 请求的资源不可用

java - 如何在 JFrame 中使用 ActionListener 刷新 JTable?

java - 数组 如何将一个数字添加到与其值相同的位置?

c++ - 虚拟接口(interface)和封装

c++ - 复制在我的 string::copy 实现中不起作用