我的教授已经给出了一个由多位构造函数创建Monthnum类来完成所有参数的任务,因为我们正在学习面向对象编程。我需要创建一个新的构造函数,它接受用户输入作为一个int值,另一个构造函数接受它作为一年中的字符串值。例如:1 = 1月和1月= 1。我知道我可以在我的主要方法中创建扫描仪,但我不确定如何让此号码被接受并打印出来。在正确的直接步骤将是非常有用的!与对象和构造函数一起使用的Java
import java.util.Scanner;
public class learningObjectsAndClasses {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
int monthNumber = input.nextInt();
String monthName = input.nextLine();
Monthnum inputMonthNumber = new Monthnum(monthNumber);
Monthnum inputMonthName = new Monthnum(monthName);
System.out.println("Please enter the month name or number: "
+ inputMonthNumber);
}
}
class Monthnum{
int Monthnum;
String monthName;
Monthnum(){
Monthnum = 1;
}
Monthnum(int whichMonth){
Monthnum = whichMonth;
if (whichMonth == 1){
System.out.println("January");
}
else if (whichMonth == 2){
System.out.println("February");
}
else if (whichMonth == 3){
System.out.println("March");
}
else if (whichMonth == 4){
System.out.println("April");
}
else if (whichMonth == 5){
System.out.println("May");
}
else if (whichMonth == 6){
System.out.println("June");
}
else if (whichMonth == 7){
System.out.println("July");
}
else if (whichMonth == 8){
System.out.println("August");
}
else if (whichMonth == 9){
System.out.println("September");
}
else if (whichMonth == 10){
System.out.println("October");
}
else if (whichMonth == 11){
System.out.println("November");
}
else if (whichMonth == 12){
System.out.println("December");
}
else
System.out.println("Invalid input");
}
Monthnum(String whichMonth){
if (whichMonth == "January"){
Monthnum = 1;
}
else if (whichMonth == "February"){
Monthnum = 2;
}
else if (whichMonth == "March"){
Monthnum = 3;
}
else if (whichMonth == "April"){
Monthnum = 3;
}
else if (whichMonth == "May"){
Monthnum = 4;
}
else if (whichMonth == "June"){
Monthnum = 5;
}
else if (whichMonth == "July"){
Monthnum = 6;
}
else if (whichMonth == "August"){
Monthnum = 7;
}
else if (whichMonth == "September"){
Monthnum = 8;
}
else if (whichMonth == "October"){
Monthnum = 9;
}
else if (whichMonth == "November"){
Monthnum = 10;
}
else if (whichMonth == "December"){
Monthnum = 11;
}
else if (whichMonth == "March"){
Monthnum = 12;
}
else
System.out.println("Invalid input");
}
}
的练习的要点是了解的构造,是吗?如果是这样,你确定你应该在这些构造函数中包含扫描器的实现吗?请记住,构造函数的目的是帮助设置一个对象以供使用。除了接收参数并将这些参数分配给对象的局部字段之外,您通常不会在构造函数中包含功能。你应该和你的老师核实你对运动的理解。 – MarsAtomic
你有阵列吗?毫无疑问,比现在拥有的if-else长链更好。 – markspace
我可能会将它改为未来的数组,但现在我只想让程序工作 – simplest