当我使用此代码生成Java中的随机5张牌时,我得到了正确的结果,但每行卡片前面都是null。这是为什么?例如,我得到nullJ♥10♥8♥Q♦9♠,我尝试了一些检查以防止它,但无济于事。如果您有任何建议,请告诉我我做错了什么?
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class RandomHandGenerator {
public static void main(String[] args) throws InterruptedException {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
String[] faces = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
char[] suits = {'♣', '♦', '♥', '♠'};
ArrayList<String> deck = new ArrayList<String>();
for (int i = 0; i < suits.length; i++) {
for (int j = 0; j < faces.length; j++) {
String temp = faces[j] + suits[i];
deck.add(temp);
}
}
int counter = 0;
int generalCounter = 0;
ArrayList<String> handsGenerated = new ArrayList<String>();
while (generalCounter < n) {
String[] currentHand = new String[5];
Random generator;
generator = new Random();
//Ako ne se pusne edin Thread.sleep dava tvurde ednakvi karti:
Thread.sleep(30);
while (counter < 5) {
int j = generator.nextInt(52);
String currentCard = deck.get(j);
if(!Arrays.asList(currentHand).contains(currentCard)) {
currentHand[counter] = currentCard;
counter++;
}
}
String buildHand = null;
for (int l = 0; l < 5; l++) {
if (currentHand[l] != null) {
buildHand += currentHand[l];
}
}
handsGenerated.add(buildHand);
counter = 0;
generalCounter++;
}
for (int i = 0; i < handsGenerated.size(); i++) {
String displayHands = handsGenerated.get(i);
System.out.println(displayHands);
}
}
}
答案 0 :(得分:6)
这是你的问题。
buildHand += currentHand[l];
您将所有卡片附加到原始值null
。
您可以这样做:
StringBuilder temp = new StringBuilder();
for (int l = 0; l < 5; l++) {
if (currentHand[l] != null) {
temp.append( currentHand[l] );
}
}
String hand = temp.toString();
关于解决方案的另一个注释。在循环和连接时最好使用StringBuilder。原因是String上的“+ =”运算符在窗帘下创建了一个StringBuilder。因此,在您当前的方法中,每个循环都在创建一个新的StringBuilder。
答案 1 :(得分:4)
变化:
String buildHand = null;
到
String buildHand = "";