我目前正在编写一个涉及随机卡片选择的程序,我想知道是否有办法让程序分别用jack,queen和king取代11,12和13号码?我可以使用if语句来检测大于10的值,但这会迫使我写4次相同的代码,这似乎适得其反。任何和所有回复都非常感谢!
int card0 = (cardGenerator.nextInt(13) + 2);
int winTest = 4;
while(winTest > 0)
{
Object[] highLowEqual = { "higher", "lower", "equal", "Quit" };
Object userChoice = JOptionPane.showInputDialog(null,
"The current card is " + card0 + ". Which do you think the next card will be? Remember: Ace is the highest possible.", "HiLo",
JOptionPane.INFORMATION_MESSAGE, null,
highLowEqual, highLowEqual[0]);
int card1 = (cardGenerator.nextInt(13) + 2);
答案 0 :(得分:3)
拥有一个知道如何自行打印的Card
课程:
public class Card
{
int rank;
// ...
public String toString()
{
switch( rank )
{
case 1: return "Ace";
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: return "" + rank;
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "INVALID CARD RANK";
}
}
}
答案 1 :(得分:0)
某些代码必须进行替换,代码必须在某处。正如khelwood所评论并由clcto回答的那样,你可以覆盖toString()方法并将替换逻辑放在那里。