Java中将char类型花色字符转换为对应完整string字符串的实现问题
Java卡牌程序花色缩写转全称解决方案
前置修复:现有代码隐性问题
- 当前Card类的
type和number属性都加了static修饰符,会导致所有Card实例共享同一份属性值,抽取第二张卡时会直接覆盖第一张卡的属性,最终输出两张卡的数值和花色完全一致,需要先删除这些多余的static修饰。
花色转换实现方案
通过映射关系把单字符缩写对应到完整花色名即可,修改后的完整代码如下:
修改后的Card实体类
public class Card { // 去掉static修饰,每个卡牌实例有独立属性 private char type; private int number; public char getType() { return type; } public void setType(char type) { this.type = type; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } // 新增转换方法:返回花色完整名称 public String getFullTypeName() { switch (this.type) { case 'c': return "Club"; case 'h': return "Heart"; case 'd': return "Diamond"; case 's': return "Spade"; default: return "Unknown"; } } }
修改后的PickTwoCards类
仅需要修改输出时调用的花色获取方法:
import java.util.Random; public class PickTwoCards { final static int CardNumbers = 13; final static char[] Types = {'c','h','d','s'}; public static void main(String args[]){ Card CardOne = ChooseCard(); System.out.println("*****Welcome to the House of Cards*****"); // 调用getFullTypeName()获取完整花色名 System.out.println("My card is the "+CardOne.getNumber()+" of "+CardOne.getFullTypeName()+"."); Card CardTwo = ChooseCard(); System.out.println("My card is the "+CardTwo.getNumber()+" of "+CardTwo.getFullTypeName()+"."); } public static Card ChooseCard(){ Card card = new Card(); card.setType(RandomType()); card.setNumber(RandomNumber()); return card; } public static char RandomType(){ int RandomTypeKeep = new Random().nextInt(Types.length); char RandomType = Types[RandomTypeKeep]; return RandomType; } public static int RandomNumber(){ int RandomCardNumber = ((int)(Math.random()*100)%CardNumbers+1); return RandomCardNumber; } }
输出效果示例
*****Welcome to the House of Cards***** My card is the 3 of Spade. My card is the 2 of Diamond.
如果需要中文花色名,仅需要把switch分支里的返回值替换为梅花、红桃、方块、黑桃即可。
内容的提问来源于stack exchange,提问作者llillillill
相关产品推荐
相关产品推荐

