如果它们使用默认值,我试图使我的开关盒再次循环 [英] I am trying to make my switch case loop back again if they get the default
本文介绍了如果它们使用默认值,我试图使我的开关盒再次循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
//Choice of choosing a dog or a cat
String pet = input.next();
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default -> System.out.println("That is not a valid option. Please choose again.");
}
input.close();
}
我找不到要使用的循环,它将循环回到情况a,直到用户使用其中一种选择进行回答为止,任何帮助都很棒!谢谢
I can't find a loop to use that would bring it back to case a and repeatedly until the user answers using one of the choices, Any help would be awesome! Thanks
推荐答案
使用 do while
循环是解决此问题的简单方法.
Using do while
loop is a simple way to solve it.
我使用了变量 repeat
进行检查,是否需要再次输入?
I used a variable repeat
to check, If I need to ask for the input again or not
另外,请注意,现在即使我添加了另一种情况(例如 case'c'
),也不需要为我的 do while
循环修改条件>
Also, note that now even If I add another case(say case 'c'
) I don't need to modify condition for my do while
loop
boolean repeat;
do {
String pet = input.next();
repeat = false;
switch (pet.charAt(0)) {
case 'a' -> {
System.out.println("What is your dog's name? ");
String dogsName = input.next();
System.out.println("Your Character's Name is: " + playerName + "\nYour Pet's Name is: " + dogsName);
}
case 'b'-> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
}
default: System.out.println("That is not a valid option. Please choose again.");
repeat = true;
}
} while(repeat);
input.close();
这篇关于如果它们使用默认值,我试图使我的开关盒再次循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文