我的代碼是這樣的:爲新變量賦值?
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
/**
*
* @author Matt
*/
public class Deck {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Random r = new Random();
String[][] DeckOfCards = new String[13][4];
int i;
int j;
int k;
String suit[] = new String[4];
String number[] = new String[13];
ArrayList draw = new ArrayList();
//setting up the deck
suit[0]="Diamonds, ";
suit[1]="Clubs, ";
suit[2]="Hearts, ";
suit[3]="Spades, ";
number[0]="Ace of ";
number[1]="Two of ";
number[2]="Three of ";
number[3]="Four of ";
number[4]="Five of ";
number[5]="Six of ";
number[6]="Seven of ";
number[7]="Eight of ";
number[8]="Nine of ";
number[9]="Ten of ";
number[10]="Jack of ";
number[11]="Queen of ";
number[12]="King of ";
//dealing the initial hand
for(j=0;j<3;j++){
for(i=0;i<12;i++){
DeckOfCards[i][j]=""+number[i]+suit[j];
draw.add(DeckOfCards[i][j]);
//System.out.println(DeckOfCards[i][j]);
}
//System.out.println("");
// System.out.println("");
}
ArrayList drawn = new ArrayList();
ArrayList hand = new ArrayList();
int u;
for(u=1;u<6;u++){
k=r.nextInt(52);
if(!drawn.contains(k)){
//System.out.println(draw.get(k));
hand.add(u+" "+draw.get(k).toString());
drawn.add(k);
}
else{
u--;
}
}
System.out.println(hand.toString());
但最後if語句:
if(!drawn.contains(k)){
hand.add(u+" "+draw.get(k).toString());
drawn.add(k);)
總是停止編譯說我需要分配新的變量返回值? k在if語句之前已經分配了一個值。當我把if語句中的隨機k語句放入if語句時,它似乎起作用,但這使它變得毫無價值,不是嗎?在編輯器本身沒有錯誤,但編譯時,它給了我這個:
線程「主」java.lang.IndexOutOfBoundsException異常:索引:41,大小:36 在java.util.ArrayList.rangeCheck(ArrayList .java:635) at java.util.ArrayList.get(ArrayList.java:411) at deck.Deck.main(Deck.java:74) Java結果:1 BUILD SUCCESSFUL(總時間:0秒)
我完全不知道如何解決這個問題。
嘗試在添加之前保存'u +「」+ draw.get(k).toString()'在一個新變量中 – Fuzzyma