gpt4 book ai didi

java - 在扑克牌程序中使用 switch 语句 (Java)

转载 作者:行者123 更新时间:2023-12-01 09:25:38 25 4
gpt4 key购买 nike

到目前为止,我已经弄清楚了我的程序,只是我不理解给我的这些说明(或者至少不理解如何执行它们)。

当我输入 10 时,它会打印出“10 of”,但是当我尝试输入 10 of Spades 的 10S 时,它只会打印出“Spades”。

希望这里有人可以给我一个解决方案或为我指明如何解决问题的正确方向:

Use a SWITCH statement to assign the result variable an initial value - the value of the card

Use a second SWITCH statement to concatenate to the result variable the card's suit"

这是代码:

import java.util.*;


public class CardConverter {

public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);

//will hold string that user will input
String card, face, suit, result;

//getting input from user and telling them correct format
System.out.println("Please enter either the number or face value intial of a card followed by the initial of it's suit (ie. QH for Queen of Hearts)");
card = keyboard.nextLine();
//gets first value
face = card.substring(0);
//sets substring for 10 only
//substring for after all single digit/letter card faces
suit = card.substring(1);


//to print face and word of
switch (face)
{
case "10":
System.out.println("10 of ");
break;
case "2":
System.out.println("2 of ");
break;
case "3":
System.out.println("3 of ");
break;
case "4":
System.out.println("4 of ");
break;
case "5":
System.out.println("5 of ");
break;
case "6":
System.out.println("6 of ");
break;
case "7":
System.out.println("7 of ");
break;
case "8":
System.out.println("8 of ");
break;
case "9":
System.out.println("9 of ");
break;
case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
}
//to print out card suit
switch (suit)
{
case "H":
System.out.println("Hearts");
break;
case "C":
System.out.println("Clubs");
break;
case "S":
System.out.println("Spades");
break;
case "D":
System.out.println("Diamonds");
break;
}
}
}

最佳答案

你的问题从card.substring(0);开始,它等于card,因为子字符串是从字符串的开头开始的。也许您想要card.charAt(0);?但这也是错误的,因为 "10S" 将包含三个字符,其中两个用于面值。

您需要专门处理三个字符的输入,或者更聪明地处理子字符串-ing。

您知道花色始终是最后一个字符,因此请使用 charAt 的字符串长度。

int suitIndex = s.length() - 1;
String suit = ""+s.charAt(suitIndex);
String face = s.substring(0,suitIndex);

您还可以简化案例

case "J":
System.out.println("Jack of ");
break;
case "Q":
System.out.println("Queen of ");
break;
case "K":
System.out.println("King of ");
break;
case "A":
System.out.println("Ace of ");
break;
default:
System.out.println(face + " of "); // handle all the numbers
break;

关于java - 在扑克牌程序中使用 switch 语句 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39863240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com