java—当用户输入2个值,中间有“and”时,它会执行一个case,我该怎么做呢?

ej83mcc0  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(431)

用户必须同时输入2个变量才能得到输出屏幕。密码有什么帮助吗?

  1. switch(cardChoice)
  2. {
  3. case 1 && 5:
  4. System.out.println("You have matched the :) card! You get 10 Points!");
  5. System.out.println("------- ------- ------- ------- ------- -------");
  6. System.out.println("| | | | | | | | | | | |");
  7. System.out.println("| :) | | 2 | | 3 | | 4 | | :) | | 6 |");
  8. System.out.println("| | | | | | | | | | | |");
  9. System.out.println("------- ------- ------- ------- ------- -------");
  10. System.out.println("------- ------- ------- ------- ------- -------");
  11. System.out.println("| | | | | | | | | | | |");
  12. System.out.println("| 7 | | 8 | | 9 | | 10 | | 11 | | 12 |");
  13. System.out.println("| | | | | | | | | | | |");
  14. System.out.println("------- ------- ------- ------- ------- -------");
  15. cardPoints = cardPoints + 10;
  16. break;
  17. default:
  18. System.out.println("Invalid Input!");
  19. }
kxxlusnw

kxxlusnw1#

如果你一定要用 switch ,有几种方法可以解决。诀窍在于 case 标签只能是单个值,因此必须以某种方式将两个输入组合成一个值,该值可以由 case 标签。
如果您只需要一个双向测试(例如,用户的选择是1和5,或者其他),那么将输入减少到yes/no就足够了。你可以这样做:

  1. int choice1, choice2;
  2. System.out.println("Enter the number of your first card choice:");
  3. choice1 = scanner.nextInt();
  4. scanner.nextLine();
  5. System.out.println("Enter the number of your second card choice:");
  6. choice2 = scanner.nextInt();
  7. scanner.nextLine();
  8. // ...
  9. switch (choice1 == 1 && choice2 == 5 ? "yes" : "no"){
  10. case "yes":
  11. // RIGHT!
  12. break;
  13. default:
  14. System.out.println("Invlid input!");
  15. }

如果这是真的 switch 有很多可能的案例,你需要更有创意。例如,你可以创建一个 String 以可预测的格式包含用户的选择,然后可以与 case . 例如:

  1. int choice1, choice2;
  2. System.out.println("Enter the number of your first card choice:");
  3. choice1 = scanner.nextInt();
  4. scanner.nextLine();
  5. System.out.println("Enter the number of your second card choice:");
  6. choice2 = scanner.nextInt();
  7. scanner.nextLine();
  8. // ...
  9. String userChoice = String.format("%02d,%02d", choice1, choice2);
  10. switch (userChoice){
  11. case "01,05":
  12. // RIGHT!
  13. break;
  14. case "02,04":
  15. // Another right answer!
  16. break;
  17. default:
  18. System.out.println("Invlid input!");
  19. }

另一种方法是将用户的选择组合成一个数字,以保留两个值的方式。例如,假设我们知道任何一个输入的有效选项都小于10。我们可以使用:

  1. int choice1, choice2;
  2. System.out.println("Enter the number of your first card choice:");
  3. choice1 = scanner.nextInt();
  4. scanner.nextLine();
  5. System.out.println("Enter the number of your second card choice:");
  6. choice2 = scanner.nextInt();
  7. scanner.nextLine();
  8. // ...
  9. switch (choice1 * 10 + choice2){
  10. case 15: // User chose 1 and 5
  11. // RIGHT!
  12. break;
  13. case 24: // User chose 2 and 4
  14. // Another right answer!
  15. break;
  16. default:
  17. System.out.println("Invlid input!");
  18. }
展开查看全部

相关问题