我剛剛開始了一個戰爭紙牌遊戲。我製作了一個套牌,然後需要重新洗牌。無論如何,我將需要.length以後纔是正確的。所以當我用這個長度的時候,當我計算的時候它應該是52,所以它得到了160的答案。這是代碼。Java Array.Length不正確
import java.util.List;
public class wargame {
public static void main(String args[]){
funtionsforwargame funtionsforwargame=new funtionsforwargame();
funtionsforwargame.instructions();
List<String> randomized_deck=funtionsforwargame.get_deck();
String[] deck_convert = randomized_deck.toArray(new String[0]);
String deck=java.util.Arrays.toString(deck_convert);
System.out.println(deck);
System.out.println(deck.length());
}
}
此外,get_deck方法創建一個甲板,作爲數組,然後轉換爲一個列表字符串,並因爲它需要進行改組返回它。所以我接下來返回列表並將其轉換回數組,然後確保它給我的套牌,而不是像ghty @ 67843那樣的東西。所以如果有人知道它爲什麼給我160而不是52,那會很有幫助。如果你不相信列表/數組中有52個,那麼這裏是get_deck方法。
public class funtionsforwargame {
public void instructions(){
System.out.println("Welcome to War!");
System.out.println("The object of the game is to collect all cards from the other person.");
System.out.println("Basically, all you do is watch and press any key to go to the next round.");
System.out.println("Good luck!!!");
}
public List<String> get_deck(){
String new_deck[]={"A","A","A","A","2","2","2","2","3","3","3","3","4","4","4","4","5","5","5","5","6","6","6","6","7","7","7","7","8","8","8","8","9","9","9","9","10","10","10","10","J","J","J","J","Q","Q","Q","Q","K","K","K","K"};
List<String> list_convert = Arrays.asList(new_deck);
Collections.shuffle(list_convert);
return list_convert;
}
}
在此先感謝。
我沒有看到你得到任何數組的'length'屬性,只是你在包含其他字符的數組的字符串表示形式上調用'length()',也是如此。逗號和空格,因此從52個1或2個字符元素中可以得到一個160個字符的字符串(類似'[A,A,2,10,...]'48個單個字符+4個雙字符+ 51次' '+'['+']'= 48 + 4 * 2 + 51 * 2 + 1 + 1 = 160個字符) – Thomas
請遵循Java命名約定(大小寫,拼寫),因爲這樣會使您的代碼可讀。例如,很難區分拼寫錯誤的'funtionsforwargame'類和拼寫錯誤的'funtionsforwargame'變量。 –