我可以在 switch 语句中使用字符串并将 .contains() 与 Java 一起使用吗?
Posted
技术标签:
【中文标题】我可以在 switch 语句中使用字符串并将 .contains() 与 Java 一起使用吗?【英文标题】:Can I use a String in a switch statement and use .contains() with Java? 【发布时间】:2022-01-14 15:20:46 【问题描述】:我正在尝试编写一个程序来玩纸牌游戏黑桃的精简版本,并且我想通过使用 switch 语句而不是重复的 if/else if/else 来提高我的代码效率。我需要这个函数来接收一个字符串(userCard),它看起来像“Spades,2”或“Diamonds,6”。我需要它将字符串末尾的数字保存为 int 数据类型。以下是有效的 if/else if/else 语句。
public static int getUserValue(String userCard)
int userValue = 0;
if (userCard.contains("4"))
userValue = 4;
else if (userCard.contains("5"))
userValue = 5;
else if (userCard.contains("6"))
userValue = 6;
else if (userCard.contains("7"))
userValue = 7;
else if (userCard.contains("8"))
userValue = 8;
else if (userCard.contains("9"))
userValue = 9;
else if (userCard.contains("10"))
userValue = 10;
else if (userCard.contains("11"))
userValue = 11;
else if (userCard.contains("12"))
userValue = 12;
else if (userCard.contains("13"))
userValue = 13;
else if (userCard.contains("1"))
userValue = 1;
else if (userCard.contains("2"))
userValue = 2;
else if (userCard.contains("3"))
userValue = 3;
return userValue;
所以我想我可以做类似的事情
public static int getUserValue(String userCard)
int userValue = 0;
switch (userCard)
case userCard.contains("4"):
userValue = 4;
break;
//etc, goes up to 13 then evaluates if 1, 2, 3.
return userValue;
它给出了一个错误,我无法将布尔值转换为字符串。 有什么办法可以改变这个或输入这个来按我想要的方式工作吗?
【问题讨论】:
看起来你应该为你的卡片使用一个对象而不是字符串。这样你就可以使用开关了。 也许您可以将字符串userCard
分开,以便您切断数字?字符串看起来总是一样吗?
错误很明显,因为contains()
方法是boolean,boolean数据类型不能用在switch-case语句中。您应该改用枚举。
使用contains
首先是一个逻辑错误。当字符串为"14"
时,contains("4")
将评估为true
。
【参考方案1】:
您应该改用 UserCard
类之类的东西:
public class UserCard
private Suit _suit;
private int _value;
// Constructor
// getter + setter
public enum Suit
DIAMONDS, HEARTS, SPADES, CLUBS;
这样您甚至不需要切换,因为您已经拥有要提取的值。你的getUserValue
很简单:
public static int getUserValue(UserCard userCard)
return userCard.getValue();
【讨论】:
我还没有完全理解类,尤其是在这种情况下,因为我还有更多的事情要做。我能否详细解释一下我的代码,以帮助我如何实现它?【参考方案2】:要勉强回答问题,不,您不能在示例中使用 switch。
switch 的 case 必须是常量。您可以使用文字值、静态最终字段或运算符来组合它们;但不调用方法。
因此,例如,case 1+2
和 case A+B
一样有效,即使 A 和 B 是字符串。
但是,有一种更好的方法可以从字符串中提取值,方法是使用 String.indexOf、String.substring 和 Integer.parseInt,或者使用正则表达式来处理更复杂的事情。 或者,更好的是,遵循其他建议创建卡片类的答案。
【讨论】:
以上是关于我可以在 switch 语句中使用字符串并将 .contains() 与 Java 一起使用吗?的主要内容,如果未能解决你的问题,请参考以下文章