我的教授已經給出了一個由多位構造函數創建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