在 java 中的 switch 语句中获取用户输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21381951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:23:45 来源:igfitidea点击:
Taking user input in a switch statement in java
提问by Eqorip
I need help making this switch statement, taking a user input in order to pick (in this case) the month that will be printed. Instead of just always printing august, how would I take a user input and let them choose the month?
我需要帮助制作这个 switch 语句,通过用户输入来选择(在这种情况下)将打印的月份。而不是总是打印八月,我将如何接受用户输入并让他们选择月份?
import java.util.Scanner;
public class SwitchDemo {
public static void main(String[] args) {
int UsrIn;
UsrIn = input.nextInt();
int month = UsrIn;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid month";
break;
}
System.out.println(monthString);
}
}
采纳答案by BetaRide
Replace
代替
int month = 8;
with
和
Scanner in = new Scanner(System.in);
System.out.println("Please entter month: ");
String msg = in.nextLine();
int month = Integer.valueOf(msg);