我需要将变量参数添加到已经有很多参数的 switch case 中的语法。下面提供了上下文。
我正在使用 switch case 将字符串答案更改为整数返回。而不是让用户回答
1.这个。
2. 别的事。
我希望答案看起来像
(是/否)
我之前用这样的代码完成过:
static public int getYN() {
String answer = "";
switch(keyboard.nextLine().substring(0, 1).toLowerCase()) {
case "y":
return 1;
case "n":
return 0;
default:
return 2;
}
}
然后使用语句:
int getAnswer = getYN();
System.out.println();
if (getAnswer == 1) {
System.out.println("Stuff.");
test = 1;
}
else {
System.out.println("Other stuff.");
System.out.println();
}
但是,我不知道在哪里将字符串答案变量放入 switch case 中。通常,如果您没有使用许多其他参数,则只需
switch(answer) {
}
最佳答案
内联检查,忘记有专门的方法来执行此检查。
char getAnswer = keyboard.next().charAt(0);
System.out.println();
if (getAnswer == 'y' || getAnswer == 'Y')
{
System.out.println("Stuff.");
test = 1;
}
else if( getAnswer == 'n' || getAnswer == 'N')
{
System.out.println("Other stuff.");
System.out.println();
}
如果你绝对必须使用开关:
char getAnswer = keyboard.next().charAt(0);
switch(getAnswer)
{
case 'y':
System.out.println("Stuff.");
test = 1;
break;
case 'n':
System.out.println("Other stuff.");
System.out.println();
break;
}
关于java - 将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20252141/