Как напечатать метод (removeTopClass) из другого класса в цикл? - PullRequest
0 голосов
/ 20 октября 2018

Сейчас я работаю над этим заданием, для которого я выполнил большую часть работы на данный момент.

public String getRankAsString() {
String[] ranks = "2", "3", "4", "5", "6", 
"7", "8", "9", "10", "J", "Q", "K", "A" 
return ranks[rank];
}

и костюм

public String getSuitAsString() {
String[] suits = { "Clubs", "Diamonds", 
"Hearts", "Spades" };
    return suits[suit];
} 

Я должен создать 2 класса в лабораторном пакете, один с именем LabApp (где будет проводиться тестирование) и DiscardPile, подкласс Stack и будет содержать метод discardTopCard, метод с именем removeTopCards, который принимает ссылку на объект Card, называемый theCard.Этот метод позволит пользователю запросить удаление всех карт вплоть до Карты, включая колоду сброса, и возвращение в массив, таким образом, тип возврата метода - Card [].Это то, что у меня есть для removeTopCard atm.

public Card[] removeTopCard(Card otherCard) throws StackEmptyException {
        Card[] theCard = new Card[size()];
        int i = 0;
        boolean check = false;

        if(isEmpty()){ //in the case that there's nothing there
          throw new StackEmptyException("Stack is Empty");
        }
        while(!isEmpty()){ //If it's not empty, pop the top card (unlimited loop that'll need to be broken by a break;)

          Card top = (Card) pop(); //Casts Card to pop, which should remove it
          theCard[i] = top; //removed and returned in an array
          i++; 
          if(top.equals(otherCard)){ //checks if the card's rank and suit are the same and stops the loop if true
            check = true;
            break; //it ends the loop if they're equivalent, all of those cards were set to top
          }
        }
        if(!check){ //if it can't find anything
          throw new StackEmptyException("Card not found");
        }
        Card[] topCards = new Card[i];

        for(int j = 0;j < i; j++){

          topCards[j] = theCard[j]; //set the discarded value array to theCard
        }
        return topCards; //should return the popped numbers
      }

I THINK это может работать просто отлично.

В LabApp, метод тестирования, который я в настоящее время используюесли метод discardPile.push работает нормально

        discardPile.push(new Card(41));

        for(int i = 0; i < discardPile.getSize(); i++) {
            Card var = discardPile.pop(); //pops the cards that are above
                System.out.println(var.getRankAsString() + " of " + var.getSuitAsString());
        }

        }
        catch (StackEmptyException SEE) {
            System.out.println("StackEmptyException: " + SEE.getMessage());
        }
        catch (StackFullException SFE) {
            System.out.println("StackFullException: " + SFE.getMessage());
       }
}
}

Он печатает желаемый вывод, без проблем

Я также должен написать вызов метода removeTopCards и протестируйте метод, передав ссылку на карту, целочисленное значение которой равно 20.

Я знаю, что пишу это так

discardPile.removeTopCard(new Card(20));

, но я не знаю, как мне поступитьо печати через цикл for.

Любая помощь будет принята с благодарностью.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...