gpt4 book ai didi

java - 如何在不创建数组的情况下检查重复值?

转载 作者:行者123 更新时间:2023-11-30 03:12:14 25 4
gpt4 key购买 nike

我有一个程序,可以根据随机数的值发 20 张牌。到目前为止,它可以处理黑桃 K、红心 2 等牌。我的工作是使用方法检查牌是否重复,但没有数组。这是我检查重复项的解决方案,但由于明显的原因而不起作用:

    public class Driver {
public static void main(String [] args) {

for (int i = 0; i < 20; i++){
Cards card1 = new Cards();
Cards card2 = card1;
if (card1 == card2) {
card1 = new Cards();
}
System.out.println(card1);
}
}
}

这是我的支持类(class):

import java.util.Random;

public class Cards {

String hearts = "Hearts";
String diamonds = "Diamonds";
String clubs = "Clubs";
String spades = "Spades";

String suit;
int cardNumber;
String numberName;
String suitName;
Random randomNum = new Random();

public Cards () {

}

public String suit() {
int theRandom = randomNum.nextInt(4);

if (theRandom == 0 ) {
suitName = "hearts";
}
else if ( theRandom == 1) {
suitName = "diamonds";
}
else if (theRandom == 2) {
suitName = "clubs";
}
else {
suitName = "spades";
}
return suitName;
}
public String number() {
int theRandomNum = randomNum.nextInt(12 + 1);

if ( theRandomNum == 1 ) {

numberName = "Ace";
}
else if ( theRandomNum == 2) {
numberName = "2";
}
else if ( theRandomNum == 3) {
numberName = "3";
}
else if ( theRandomNum == 4) {
numberName = "4";
}
else if ( theRandomNum == 5) {
numberName = "5";
}
else if ( theRandomNum == 6) {
numberName = "6";
}
else if ( theRandomNum == 7) {
numberName = "7";
}
else if ( theRandomNum == 8) {
numberName = "8";
}
else if ( theRandomNum == 9) {
numberName = "9";
}
else if ( theRandomNum == 10) {
numberName = "10";
}
else if ( theRandomNum == 11) {
numberName = "Jack";
}
else if ( theRandomNum == 12) {
numberName = "Queen";
}
else if ( theRandomNum == 13) {
numberName = "King";
}
return numberName;
}

public String toString()
{
if (number() == "null") {
return ("3" + " of " + suit());
}

return (number() + " of " + suit());
}
}

最佳答案

使用大字符串来存储已选择的卡片:

String cards = "";

for(int i = 0; i < 20; i++)
{
Cards card = new Cards();
while(cards.contains(card.toString()))
card = new Cards(); //keep generating a random card until it's a new card
cards += card.toString(); //add the card to the string of cards
System.out.println(card);
}

此代码将进入您的 Driver 类的 main 方法

关于java - 如何在不创建数组的情况下检查重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33394041/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com