我正在试验用Java中的switch语句,我写了下面的程序,打印出一周中一天的相应数字。我在调试程序时遇到了麻烦。下面是这样的。
public static void main(String[] args) {
String str;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your day of the week: ");
scan.next();
switch(str) {
case "Monday":
System.out.println("The number corresponding to your chosen day is: 1");
break;
case "Tuesday":
System.out.println("The number corresponding to your chosen day is: 2");
break;
case "Wednesday":
System.out.println("The number corresponding to your chosen day is: 3");
break;
case "Thursday":
System.out.println("The number corresponding to your chosen day is: 4");
break;
case "Friday":
System.out.println("The number corresponding to your chosen day is: 5");
break;
case "Saturday":
System.out.println("The number corresponding to your chosen day is: 6");
break;
case "Sunday":
System.out.println("The number corresponding to your chosen day is: 7");
break;
default:
throw new IllegalArgumentException("Invalid day of the week");
}
}
}
错误指出 "str my not have been initialized"。然而,当我试着操作这个并初始化了 str
像这样。
String str = "Monday";
我每次都得到同样的输出。
The number corresponding to your chosen day is: 1
任何帮助都将是非常感激的,非常感谢你!
代码应该是这样的会工作。初始的本地变量值和从扫描对象的赋值。
public static void main(String[] args) {
String str = null; // initialisation
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your day of the week: ");
str = scan.next(); //assignment
switch(str) {
case "Monday":
System.out.println("The number corresponding to your chosen day is: 1");
break;
case "Tuesday":
System.out.println("The number corresponding to your chosen day is: 2");
break;
case "Wednesday":
System.out.println("The number corresponding to your chosen day is: 3");
break;
case "Thursday":
System.out.println("The number corresponding to your chosen day is: 4");
break;
case "Friday":
System.out.println("The number corresponding to your chosen day is: 5");
break;
case "Saturday":
System.out.println("The number corresponding to your chosen day is: 6");
break;
case "Sunday":
System.out.println("The number corresponding to your chosen day is: 7");
break;
default:
throw new IllegalArgumentException("Invalid day of the week");
}
}