This question already has answers here:
Case insensitive matching in Java switch-case statement
(4个答案)
去年关闭。
如何仅使用“ switch and if”在Java解决方案中创建这样的输入“ January”,“ january”,“ JANUARY”,“ janUARY”以及任何其他大小写组合,都将被视为“ January”,并且在所有情况下均输出1。做过程序,但是它只能使用相同的输入词,也许可以解决这个问题。
然后,大小写应为大写,例如:
(4个答案)
去年关闭。
如何仅使用“ switch and if”在Java解决方案中创建这样的输入“ January”,“ january”,“ JANUARY”,“ janUARY”以及任何其他大小写组合,都将被视为“ January”,并且在所有情况下均输出1。做过程序,但是它只能使用相同的输入词,也许可以解决这个问题。
import java.util.Scanner;
public class nameMonth
{
public static void main(String[] args)
{
String month;
int nrMonth;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter a month");
month = keyboard.nextLine();
switch (month)
{
case "January":
System.out.println("Your month is January");
nrMonth = 1;
break;
case "February":
System.out.println("Your month is February");
nrMonth = 2;
break;
case "March":
System.out.println("Your month is March");
nrMonth = 3;
break;
case "April":
System.out.println("Your month is April");
nrMonth = 4;
break;
case "May":
System.out.println("Your month is May");
nrMonth = 5;
break;
case "June":
System.out.println("Your month is June");
nrMonth = 6;
break;
case "July":
System.out.println("Your month is July");
nrMonth = 7;
break;
case "August":
System.out.println("Your month is August");
nrMonth = 8;
break;
case "September":
System.out.println("Your month is September");
nrMonth = 9;
break;
case "October":
System.out.println("Your month is October");
nrMonth = 10;
break;
case "November":
System.out.println("Your month is November");
nrMonth = 11;
break;
case "December":
System.out.println("Your month is December");
nrMonth = 12;
break;
default:
System.err.println("Your month is wrong");
break;
}
}
}
最佳答案
用这个:
switch (month.toUpperCase()) {
然后,大小写应为大写,例如:
case "JANUARY":
System.out.println("Your month is January");
nrMonth = 1;
break;
关于java - 如何仅使用“switch and if”这样的输入(例如“January”或“janUARY”)在Java解决方案中进行创建,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52842974/
10-08 20:36