[英]Array out of bounds java
我正在嘗試編寫一個代碼,在其中構造52張紙牌堆,然后將紙牌分發給n個玩家(某些玩家可能會有多余的紙牌)。 贏家是獲得黑桃A牌的人。
這是我的程序:
public class CardGame {
public static void main(String[] args) {
System.out.println("Enter the number of players");
int numofPlayers = Integer.parseInt(args[0]);
CardPile gameDeck = CardPile.makeFullDeck();
CardPile [] players = new CardPile[numofPlayers];
for (int i=0;i<numofPlayers;i++) {
int numofnum = i%numofPlayers;
players[i] = new CardPile();
}
for (int i=0;i<52;i++) {
int numofnum =i%numofPlayers;
CardPile curPlayer = players[i%numofPlayers];
Card nextCard = gameDeck.get(i);
players[numofnum].addToBottom(nextCard);
}
for (int i=1;i<numofPlayers;i++) {
if (players[i].find(Suit.SPADES, Value.ACE) != -1) {
System.out.println("Player" + i + "has won!");
}
}
}
}
我一直越界錯誤。 我在該程序中調用的方法寫得很好,因此問題應該出在此代碼上。 有人可以幫忙嗎?
編輯:這是我得到的錯誤
java.lang.ArrayIndexOutOfBoundsException: 0
at CardGame.main(CardGame.java:5)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
>
謝謝 !
您要的是玩家人數,但不是在閱讀輸入內容; 取而代之的是,您正在讀取程序的args來確定播放器的數量。
可能您沒有在命令行上傳遞任何參數,因此當您要求args[0]
時會引發異常。
您需要研究從程序中的控制台獲取輸入,或者在運行程序時傳遞播放器的數量(在這種情況下,可以刪除println)。
正如Alex在回答中所解釋的那樣,其原因是因為您在運行代碼時沒有傳遞參數。 如果您希望代碼能正常工作,則必須按照以下步驟運行代碼:
java CardGame 5
上面的代碼執行CardGame類,並將5作為參數傳遞給args [0]中的main方法。 如果您通過某個IDE執行代碼,則假設使用Eclipse,那么請參閱此問題的答案以弄清楚如何傳遞參數。
如果您希望替換上面的代碼(以接受用戶輸入),請替換以下行
int numofPlayers = Integer.parseInt(args[0]);
與以下行
Scanner input= new Scanner(System.in);
int numofPlayers = input.nextInt();
執行代碼后,將要求您輸入玩家人數並輸入+ ve整數值。
如果使用“掃描程序”選項,請確保使用非整數(以及負整數)的值來驗證輸入。 例如,如果提供的輸入不是整數,那么您將得到InputMismatchException
因此,用try{} and catch(){}
包圍輸入以捕獲上述異常將是正確的處理方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.