基本上它是一个卡点计数器,它根据你的卡计算积分。但是,我还必须承认有人可能甚至没有牌。所以我的问题是如何告诉我的程序空手?
我在考虑合并这种方法
hand.isEmpty();
但是甚至可以将方法放在方法中吗?
这是我的代码
public int countDeadwood(String hand) {
int deadwood = 0;
for(int i = 0; i < hand.length() ; i = i + 1)
{
if (hand.charAt(i)=='A')
deadwood = deadwood + 1;
if (hand.charAt(i)=='K')
deadwood = deadwood + 10;
if (hand.charAt(i)=='Q')
deadwood = deadwood + 10;
if (hand.charAt(i)=='J')
deadwood = deadwood + 10;
if (hand.charAt(i)== 'T')
deadwood = deadwood + 10;
if (hand.charAt(i)== 9)
deadwood = deadwood + 9;
if (hand.charAt(i)== 8)
deadwood = deadwood + 8;
if (hand.charAt(i)== 7)
deadwood = deadwood + 7;
if (hand.charAt(i)== 6)
deadwood = deadwood + 6;
if (hand.charAt(i)== 5)
deadwood = deadwood + 5;
if (hand.charAt(i)== 4)
deadwood = deadwood + 4;
if (hand.charAt(i)== 3)
deadwood = deadwood + 3;
if (hand.charAt(i)== 2)
deadwood = deadwood + 2;
}
return deadwood;
}
或者还有另一种方法可以空手添加吗?
答案 0 :(得分:0)
首先,我想指出你用来计算死木值的逻辑不是很优雅;至少你应该使用if-else,尽管以下可能是更好的方法。当然,这假设每个角色代表一张牌,只能遇到有效牌。
char c = hand.charAt(i);
if (c == 'A') {
value += 1;
} else if (Character.isDigit(c)) {
value += c - '0';
} else {
value += 10;
}
要确认某人是否有任何卡片,您可以检查是否有卡片。
int deadwood = 0;
if (hand.isEmpty()) {
System.out.println("You have no cards");
} else {
for (int i = 0; i < hand.length(); i++) {
char c = hand.charAt(i);
if (c == 'A') {
deadwood += 1;
} else if (Character.isDigit(c)) {
deadwood += c - '0';
} else {
deadwood += 10;
}
}
System.out.println("You have " + deadwood + " points");
}
return deadwood;
但是,如果您只需要通过返回0来确认某人没有牌,那么您实际上并不需要做任何事情。
int deadwood = 0;
for (int i = 0; i < hand.length(); i++) {
char c = hand.charAt(i);
if (c == 'A') {
deadwood += 1;
} else if (Character.isDigit(c)) {
deadwood += c - '0';
} else {
deadwood += 10;
}
}
return deadwood;
答案 1 :(得分:-1)
只需检查使用isEmpty()方法的方法。
示例:
if(hand.isEmpty())
{
//System.out.println("Sorry you have no cards");
break; //break out of the entire for loop
}