Java 使根据相应数字打印月份名称的程序更短
此程序要求用户输入任何等于或介于1-12之间的数字。然后,它将数字转换为将要打印的消息(复制程序以便自己查看)。有没有办法缩短代码Java 使根据相应数字打印月份名称的程序更短,java,Java,此程序要求用户输入任何等于或介于1-12之间的数字。然后,它将数字转换为将要打印的消息(复制程序以便自己查看)。有没有办法缩短代码 import javax.swing.JOptionPane; public class NumOfMonth { public static void main(String[] args) { int num = Integer.parseInt (JOptionPane.showInputDialog ("Enter any number e
import javax.swing.JOptionPane;
public class NumOfMonth {
public static void main(String[] args) {
int num = Integer.parseInt (JOptionPane.showInputDialog ("Enter any number equal to or between 1-12 to display the month"));
switch (num)
{
case 1:
System.out.println ("The name of month number 1 is January");
break;
case 2:
System.out.println ("The name of month number 2 is February");
break;
case 3:
System.out.println ("The name of month number 3 is March");
break;
case 4:
System.out.println ("The name of month number 4 is April");
break;
case 5:
System.out.println ("The name of month number 5 is May");
break;
case 6:
System.out.println ("The name of month number 6 is June");
break;
case 7:
System.out.println ("The name of month number 7 is July");
break;
case 8:
System.out.println ("The name of month number 8 is August");
break;
case 9:
System.out.println ("The name of month number 9 is September");
break;
case 10:
System.out.println ("The name of month number 10 is October");
break;
case 11:
System.out.println ("The name of month number 11 is November");
break;
case 12:
System.out.println ("The name of month number 12 is December");
break;
default:
System.out.println ("You have entered an invalid number");
}
}
}
是的,使用:
返回月字符串数组
我强烈建议您在访问数组之前检查边界。import javax.swing.JOptionPane;
import javax.swing.JOptionPane;
public class NewClass {
public static void main(String[] args) {
String[] months = new String[]{
"",
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC"
};
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter any number equal to or between 1-12 to display the month"));
if (num >= 1 && num <= 12) {
System.out.println("Name of month is " + months[num]);
} else {
System.out.println("INVALID ENTRY");
}
}
}
公共类新类{
公共静态void main(字符串[]args){
字符串[]个月=新字符串[]{
"",
“简”,
“二月”,
“三月”,
“四月”,
“五月”,
“六月”,
“七月”,
“八月”,
“九月”,
“十月”,
“11月”,
“十二月”
};
int num=Integer.parseInt(JOptionPane.showInputDialog(“输入任何等于或介于1-12之间的数字以显示月份”);
如果(num>=1&&num如果您的程序运行正常,并且您正在寻找一个审阅,那么它可能更适合。此外,您可以查看枚举
或数组
或映射
。捕捉越界值不应该被忽略。经验丰富的读者应该注意,此方法根据有效值而改变返回值当然,只是让他们知道这不是1:1的简化。
import javax.swing.JOptionPane;
public class NewClass {
public static void main(String[] args) {
String[] months = new String[]{
"",
"JAN",
"FEB",
"MAR",
"APR",
"MAY",
"JUN",
"JUL",
"AUG",
"SEP",
"OCT",
"NOV",
"DEC"
};
int num = Integer.parseInt(JOptionPane.showInputDialog("Enter any number equal to or between 1-12 to display the month"));
if (num >= 1 && num <= 12) {
System.out.println("Name of month is " + months[num]);
} else {
System.out.println("INVALID ENTRY");
}
}
}