当用户输入 2 个中间带有"and"的值时,我该如何执行一个案例?



用户必须同时输入两个变量才能获得输出屏幕。有关于代码的帮助吗?

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

如果必须使用switch,可以通过以下几种方法来实现。诀窍是case标签只能是单个值,因此必须以某种方式将两个输入组合为一个值,该值可以由case标签匹配。

如果你只需要一个双向测试(例如,用户的选择是1和5,或者其他什么(,那么将输入减少到是/否答案就足够了。你可以这样做:

int choice1, choice2;
System.out.println("Enter the number of your first card choice:");
choice1 = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter the number of your second card choice:");
choice2 = scanner.nextInt();
scanner.nextLine();
// ...
switch (choice1 == 1 && choice2 == 5 ? "yes" : "no"){
case "yes":
//  RIGHT!
break;
default:
System.out.println("Invlid input!");
}

如果它将是一个真正的switch,有多种可能的情况,你需要更有创意。例如,您可以创建一个String,其中以可预测的格式包含用户的选择,然后可以将其与case进行匹配。例如:

int choice1, choice2;
System.out.println("Enter the number of your first card choice:");
choice1 = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter the number of your second card choice:");
choice2 = scanner.nextInt();
scanner.nextLine();
// ...
String userChoice = String.format("%02d,%02d", choice1, choice2);
switch (userChoice){
case "01,05":
//  RIGHT!
break;
case "02,04":
// Another right answer!
break;
default:
System.out.println("Invlid input!");
}

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

int choice1, choice2;
System.out.println("Enter the number of your first card choice:");
choice1 = scanner.nextInt();
scanner.nextLine();
System.out.println("Enter the number of your second card choice:");
choice2 = scanner.nextInt();
scanner.nextLine();
// ...
switch (choice1 * 10 + choice2){
case 15:   // User chose 1 and 5
//  RIGHT!
break;
case 24:   // User chose 2 and 4
// Another right answer!
break;
default:
System.out.println("Invlid input!");
}

最新更新