如何解决我试图让我的开关盒再次循环,如果他们让用户获得默认值
我找不到要使用的循环,该循环会将其带回到切换用例的开头,并反复出现,直到用户使用其中一种选择进行回答为止,任何帮助都很棒!谢谢。 (我也尝试过使用有人建议的do-while循环,但这似乎在默认情况下是垃圾邮件。)((我留在代码中))
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: ");
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
//Choice of choosing a dog or a cat
String pet = input.next();
do {
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);
break;
}
case 'b' -> {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;
}
default -> System.out.println("That is not a valid option. Please choose again.");
}
} while (pet.charAt(0) != 'a' && pet.charAt(0) != 'b');
input.close();
}
解决方法
您需要在do循环中获取Cat / Dog的输入(选项a或选项b),以便在输入错误之后可以请求更新的输入。如下:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println(" Welcome To The Choices Game... ");
System.out.println("Please enter your name: ");
String playerName = input.nextLine();
System.out.println("What is " + playerName + "'s" + " favorite pet?");
System.out.println("a. Dog \nb. Cat");
// Here is change in code
String pet = null;
do {
// Choice of choosing a dog or a cat
// Here is change in code
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);
break;
}
case 'b': {
System.out.println("What is your cat's name? ");
String catsName = input.next();
System.out.println("Character Name: " + playerName + "\nPet Name: " + catsName);
break;
}
default: {
System.out.println("That is not a valid option. Please choose again.");
}
}
} while (pet.charAt(0) != 'a' && pet.charAt(0) != 'b');
input.close();
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。