我正在制作一个使用ArrayList的小卡牌程序。其中有一个限制是我必须使用Arraylist类型来“发牌”。我遇到的问题是我不知道如何从ArrayList中返回特定的索引值。请参见以下代码:
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0); //<-- This doesn't work, Netbeans says that it is a string type
//not an ArrayList type. The only thing it will actually
//allow me to return is:
return.al; // But this doesn't work, I don't need to return the whole list,
// just the first element, but Netbeans calls that a String type, not
// ArrayList
那么我该如何返回 List 的第一个项目并确保它的类型正确?其他代码并不重要,只需要关注方法类型和返回语句即可。
编辑:根据请求进行了修改。
package deckofcards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Deck{
ArrayList<String> al = new ArrayList<>();
public void shuffle(){
Collections.shuffle(al);
}
public String displayDeck(){
String returnDeck = "";
for(int i = 0; i < al.size(); i++){
String printDeck = al.get(i);
returnDeck += printDeck;
}
return returnDeck;
}
public ArrayList deal(int n, boolean up){
Card card0 = new Card();
boolean cardFace = card0.state(up);
return al.get(0);
}
public void populate(){
al.add(0, "Ace of Spades");
al.add(1, "Two of Spades");
al.add(2, "Three of Spades");
//yadaa yadaa
al
的声明。它是什么? - Jason CArrayList
,那么你必须将结果放入ArrayList
中并返回它。此外,你不应该使用未经限定的(即原始的)泛型类型。它是一个ArrayList<Someclass>
,知道Someclass
应该是什么会有所帮助。你没有提供足够的信息。 - Jim Garrisonn
张牌组成的 ArrayList。我认为你需要再阅读一下你的任务说明。 - Radiodefdeck0.deal(int n, boolean up)
,然后必须打印出n张牌,声明它们是正面朝上还是背面朝上,并从列表中删除这些元素。我不知道如何在测试类端执行此操作,因此我认为我必须在方法本身中执行此操作,如上所述。 - user3066571