2015-05-06 4 views
-1

Я пытаюсь получить конкретную информацию о карте в списке массивов.Извлечь информацию об объекте из определенной позиции в arraylist?

Каждый объект в ArrayList имеет 2 характеристики:

value // such as ace, 10, jack, 4 
suit // diamonds, clubs etc 

меня такое ArrayList, который держит перемешиваются колоду карт, которая печатает как это (метод работает, это только для отображения объектов):

as qd ts 4s ad 5d jd 2s 3h ac 2c 5c 9h 4d 6c 9c 8d 7h 3d 7d 8s qs jc ks jh 3s 7s td 6d 9d kc 8h 4c 4h 8c 2h qc 6s qh 
// etc etc, arraylist holds 52 objects (the cards) 

Когда карта выдаются из перемешиваются пакет (перемешиваются массив выше), она удаляет карту из перемешиваются массива и перемещает его в массив флопа, из которых имеет размер, равный общую сумму объектов внутри.

Метод сделки для контекста

private void dealCard(){ 
    //TODO 
    int totalLeftOver = 0; // used to count the cards left in the shuffled-but-not-dealt pack 
    Card topCard = shuffledPack.get(0); 
    //String dealtCard = topCard.getValue() + topCard.getSuit(); 
    shuffledPack.remove(0); 
    theFlop.add(topCard); 
    System.out.print("Cards on the flop: "); 
    for(Card dealt : theFlop){ 
     String definitelyDealt = dealt.getValue() + dealt.getSuit() + " "; 
     System.out.print(definitelyDealt); 
    } 
    System.out.println("\n"); 
    for(Card card : shuffledPack){ // for loop to count how cards haven't been dealt 
     totalLeftOver++; 
    } 
    System.out.println("Total number of cards not dealt: " + totalLeftOver); // show how many cards haven't been dealt to the player 
} 

Я сейчас пытаюсь получить значение и костюм конкретной карты в списке массива флопа, в зависимости от позиции. Для простоты предположим, что я хочу получить информацию для последней раздаточной карты. Вот что я в настоящее время, который определяет размер флопа:

private void makeMovePreviousPile(){ 
    int lastDealtCardPos = theFlop.size(); //allows us to see how many cards have been dealt, are you even trying to challenge us Chris? 
    int previouslyDealtCardPos = lastDealtCardPos - 1; 

    if(lastDealtCardPos != 0){ // check that the deck has been shuffled 
     String lastCardDealt = lastDealtCardPos.getValue() + lastDealtCardPos.getSuit(); // this doesn't work, its where I'm stuck. 
    } 
    else { // if it hasn't been shuffled we shun the user. 
     System.out.println("Are you sure you shuffled the deck before dealing? Stop trying to cheat."); 
     System.out.println("Next time we play Monopoly you won't be the banker. \n"); 
    } 
    //System.out.print(totalDealtCards + " "); // should be equal to the amount of cards we've dealt, if not we've got a problem Huston. 
    //System.out.print("Total cards on the flop: " + lastDealtCardPos + " "); // checking to see that its working as intended 
    //System.out.print("Previous card dealt: " + previouslyDealtCardPos); 
} 

Теперь, когда мы знаем, размер флопа (сколько раздачи карт) и положение последней карты в массиве (в данном случае lastDealtCardPos), как мы могли бы извлечь из этой позиции информацию о карте (например, «ах» для Ace of Hearts)?

Раньше при езде на велосипеде через пакет и распечатывания каждую карту, как он будет добавлен в массив, я использовал эти два метода (которые работают):

public String getSuit() { 
    return suit; 
} 

    public String getValue() { 
    return value; 
} 

ответ

1

Ну, если предположить, что флоп действительно ArrayList, а не Array (ваш вопрос название и противоречат тело), ​​вы всегда можете сделать

theFlop.get(lastDealtCardPos).getSuit(); 
theFlop.get(lastDealtCardPos).getValue(); 

Хотя на основе кода, вы должны помнить, что size() не 0 индексируются. Поэтому вы должны установить lastDealtCardPos в size()-1

+0

Это сработало, большое вам спасибо! –

Смежные вопросы