我是新來的java,我對我的進步感到震驚。java-輸出不同的隨機字符串
我有一個方法可以在1-13和'cdsh'之間生成一個隨機字符串。將這兩個字符串結合在一起,它將決定我在程序中收到的卡片類型。
我會隨機四次,如果有任何結果相同, 程序會再次隨機。
e.g random output
s1(spades of 1)
h3(hearts of 3)
s1(spades of 1) <-- duplicated! it will random again and produce and different string.
d1(diamond of 1)
public static String randomizedCard() {
int randomInt;
String rank = null;
String suits = null;
String cardType;
Random randomGenerator = new Random();
randomInt = randomGenerator.nextInt(13);
if(randomInt == 0)
{
randomInt = randomGenerator.nextInt(13);
}
rank = Integer.toString(randomInt);
char[] chars = "cdhs".toCharArray();
StringBuilder sb = new StringBuilder();
Random randomChar = new Random();
char c = chars[randomChar.nextInt(chars.length)];
sb.append(c);
suits = sb.toString();
cardType = suits + rank;
System.out.println(cardType);
return cardType;
}
public static void main(String[] args) {
String[] ic = new String[4];
for(int i = 0; i < 4; i++) {
/*from here onwards I get confused on how should I write the code such that
if it randoms the same string, it will the random method (randomizedCard)
till it produce all four different random numbers without duplicate and store
it into the array.*/
//store the random string to an array
ic[i] = randomizedCard();
// if it's the same random again
if(ic[i] == randomsizedCard()) {
randomsizedCard();
ic[i] = randomsizedCard();
}
}
}
我應該怎麼寫代碼,這樣如果它隨機量相同的字符串,它會隨機方法(randomizedCard),直到它產生四個不同的隨機數不重複,並將其存儲到數組?
那麼你的問題是什麼?如果您想進行代碼審查,請在[代碼審查](http://codereview.stackexchange.com/)上嘗試。在此處詢問_specific_問題。 –
看起來實際問題在第二個代碼部分的評論中。 –