我如何在不打印出完全相同的组合的情况下让控制台打印出1套西装和1个号码?
这是我正在创建的扑克游戏的开始。
import java.util.Scanner;
public class Poker {
public static void main(String[] args) {
int Cards_Per_Player= 5;
int Num_Cards = 5;
int Num_Players = 5;
int Num_Attempts = 0;
String suit = "deck";
String value = "Ace";
Scanner input = new Scanner(System.in);
System.out.println("welcome to the den");
System.out.println("only 2 to 5 players are allowed in here.");
System.out.println("How many of you are there?");
Num_Players = input.nextInt();
Num_Attempts = 1;
while(Num_Players < 2 | Num_Players > 5) {
if(Num_Players < 2 | Num_Players > 5)
System.out.println("That is wrong try again.");
Num_Players = input.nextInt();
Num_Attempts++;
}
System.out.println("alright, we got "+ Num_Players + " Here");
for(int i=1; i <= Num_Players; i++) {
System.out.println("Player" + i);
for (int card = 1; card <= Num_Cards; card++) {
double s1 = Math.random();
double v1 = Math.random();
int Suit = (int)(s1 * 4) + 1;
int Cards = (int)(v1 * 13);
switch (Suit)
{
case 1: suit = "Hearts"; break;
case 2: suit = "Clubs"; break;
case 3: suit = "Spades"; break;
case 4: suit = "Diamond"; break;
}
switch (Cards)
{
case 1: value = "Ace"; break;
case 2: value = "2"; break;
case 3: value = "3"; break;
case 4: value = "4"; break;
case 5: value = "5"; break;
case 6: value = "6"; break;
case 7: value = "7"; break;
case 8: value = "8"; break;
case 9: value = "9"; break;
case 10: value = "10"; break;
case 11: value = "Jack"; break;
case 12: value = "Queen"; break;
case 13: value = "King"; break;
}
System.out.println(" " + value + " of " + suit + ",");
}
System.out.println();
}
}
}
如果要确保输出不会重复自身,我建议使用java.util.ArrayList
。例如,如果在切换后输入java.util.ArrayList
和suit == "Hearts"
,则可以执行value == "10"
,并且在每次打印卡之前,都可以调用java.util.List <Integer> suitList = new ArrayList<>()
。 (当然,您也必须对值进行此操作,最好是使自己的类包含两个变量而不是创建2个数组列表)
潜在的实现:
suitList.add(suit)
之前
调用System.out.println(" "+value+" of "+suit+",");
,值也相同。
和for循环遍历ArrayList以检查是否已打印同一张卡。
您有很多选择,但是我会使用suitList.add(suit)
来跟踪已经看到的卡。您可以使用“西服号码”格式或以Set
格式创建Set<String> cards
,然后调用Set<Card> cards
以查看是否找到了生成的卡。
顺便提一下,Java中的约定是将所有变量以小写字母开头,因为像这样的名称在传统上是为类保留的。