Удаление карты из матроса

#java #arrays #class #while-loop #boolean

#java #массивы #класс #цикл while #логическое

Вопрос:

Всем ада,

Обновление: я добавил остальную часть своего кода. Я не хотел добавлять слишком много кода, чтобы StackOverflow не позволял мне публиковать. Ценю вашу помощь!

В моем назначении указано «удалить — удалить один экземпляр карты с заданным значением из палубной команды и вернуть удаленный экземпляр».

Карта эквивалентна значению мастей.

Я инициализировал полный набор класса DeckHand, который содержит: Туз червей, ….., Туз пик, ……, Туз бубен, ….., Туз треф.

Мне было указано, что параметр представляет собой значение (представленное в виде целого числа) и в методе delete, как только он находит первый экземпляр значения, создает карту и удаляет из палубного экипажа.

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

Я был бы признателен за некоторую помощь. Спасибо! введите описание изображения здесь// Основная программа

 public class Test
{
   private static final int SUIT = 4;
   private static final int VALUE = 13;
   public static Scanner keyboard = new Scanner(System.in);

   public static void main(String[] args)
   {
      //Scanner keyboard
      // Scanner keyboard = new Scanner(System.in);
      
      //Variables needed from User
      char decision = 'Y';
      int optionSelected;
      int chooseDeck;
      
      //Display Opening Messasge
      System.out.println("Welcome to Phase I DeckHand Implementationn");
      System.out.println("Please note that DeckOne is fully intialized and DeckTwo is empty.");
      
      //Declare two instances of the DeckHand
      DeckHand deckOne = new DeckHand();
      DeckHand deckTwo = new DeckHand();
      
      //Initialize one Deck - deckOne
      setDeck(deckOne);
      
      while(!(decision == 'N' || decision == 'n'))
      {
         //Display Menu
         displayMenu();
         
         //Select Option from Menu
         optionSelected = chooseMenuOption();
         
         //Select Deck to Manipulate
         chooseDeck = chooseDeckHand();
         
         //Perform Option
         if(chooseDeck == 1)
         {
            performOption(optionSelected, deckOne);
         }
         else if (chooseDeck == 2)
         {
            performOption(optionSelected, deckTwo);
         }
                           
         System.out.println("Would you like to continue with this Program?");
         System.out.print("Select y/Y for Yes or Select n/N for No: " );
         decision = keyboard.next().charAt(0);
         printLine();
         if(decision == 'n' || decision == 'N')
         {
            System.out.println("Thank you for using this Program");
         }    
      }     
   }
   
/*
The displayMenu Method will display the menu to the user
*/ 
   public static void displayMenu()
   {
      System.out.println("Please select from the options below: ");
      System.out.println("Option 1: Initialize An Empty DeckHand");
      System.out.println("Option 2: Insert a Card");
      System.out.println("Option 3: Delete a Card");
      System.out.println("Option 4: Delete Any Random Card");
      System.out.println("Option 5: Count(Shows how many times a specific Card is in the Deck)");
      System.out.println("Option 6: Get Size (Number of Cards in a Deck)");
      System.out.println("Option 7: Print Deck (Prints all Cards in a Deck)n");
   }
/*
The chooseMenuOption Method will ask the user to choose an option from the Menu.
@return option - Will return either 1-7 in order to perfom the operation from the Menu.
*/    
   public static int chooseMenuOption()
   {      
      //Variable for User
      int option;
      
      //Message
      System.out.print("Please select an option from the Menu: ");
      option = keyboard.nextInt();
      printLine();
      return option;  
   }
/*
The chooseDeckHand Method will ask the user choose which Deck to manipulate
either DeckOne or DeckTwo
@return choose - If user selects one they will choose DeckOne. If user selects two they will choose DeckTwo
*/   
   public static int chooseDeckHand()
   {
      DeckHand deckChosen = new DeckHand();
      int choose;
      
      System.out.println("Please select which Deck you would like to manipulate.");
      System.out.println("Select (1) for DeckOne or Select (2) for DeckTwo.");
      System.out.print("Please select Deck: ");
      choose = keyboard.nextInt();
      printLine();
      return choose;
   }
   
/*
The performOption Method will perform the option selected from the menu to the DeckHand selected.
@param option - The option chosen from the user based on the menu.
@param deck - The DeckHand the user chose to use
*/    
   public static void performOption(int option, DeckHand deck)
   {            
      //Switch Statement
      switch(option)
      {
         case 1:
            deck = new DeckHand();
            System.out.println("Initialized an Empty DeckHand");
            break;
            
         case 2:
            System.out.println("Insert a Card.");
            Card addCard = createCard();
            deck.insert(addCard);
            System.out.println("A Card has been added to this Deck.");
            printLine();
            break;
            
         case 3:
            System.out.println("Delete a Card.");
            int value;
            System.out.print("Please enter a value to Delete: ");
            value = keyboard.nextInt();
            
            //Check to see if the Card they entered exists in the list
            if(deck.count(value) == 0)
            {
               System.out.println("Unfortunately, this card does not exist.");
            }
            else
            {
               System.out.println("Deleted "   deck.delete(value));
               printLine();
            }
            break;
            
         case 4:
            System.out.println("Delete Any Random Card.");
            System.out.println("Deleted "   deck.deleteAny());
            printLine();
            break;
            
         case 5:
            System.out.println("Count(Shows how many times a specific Card is in the Deck)");
            Card newCard = createCard();
            System.out.println("The number of times this card is in this deck is "   deck.count(newCard)   "time(s)");
            printLine();
            break;
            
         case 6:
            System.out.println("Get Size (Number of Cards in a Deck)");
            System.out.println("The number of cards in this Deck is "   deck.getSize()   "card(s).");
            printLine();
            break;
            
         case 7:
            System.out.println("Print Deck (Prints all Cards in a Deck)");
            System.out.println(deck.toString());
            break;          
      }
   }
   
/*
The createCard Method will create a Card if the user selects the Insert Card option
@newCard - returns a new Card that will be used in the Insert Card option
*/ 
   public static Card createCard()
   {  
      //Variables needed from User
      int suit;
      int value;
      
      System.out.println("Please create a Card.n");
      System.out.print("Enter a suit: ");
      suit = keyboard.nextInt();
      System.out.print("Enter a value: ");
      value = keyboard.nextInt();
      
      //Create a Card 
      Card newCard = new Card(suit, value);
      
      //Return the Card
      return newCard;  
   }
   
/*
The setDeck Method will initialize the DeckHand for a particular deck
@param deck - DeckHand object
*/    public static void setDeck(DeckHand deck)
   {
      //Set _suit values
      for(int i = 1; i <= SUIT; i  )
      {
         for(int j = 1; j <= VALUE; j  )
         {
            Card newCard = new Card(i,j);
            deck.insert(newCard);
         }
      }
   }
   
/*
The printLine Method will perform the System.out.println()
*/    public static void printLine()
   {
      System.out.println();
   }
}

class DeckHand
{
   //Data Members
   private static final int FIXED = 52;
   private Card[] _list = new Card[FIXED]; // Creates an Array of 52 Cards
   private int _size; //Size of the Card _list
   private static Random randomNumbers = new Random(); //Random Object

   
   //Constructor
   public DeckHand()
   {
      _list = new Card[FIXED];
      _size = 0; 
   }
   
   //insert Method: insert a given Card in the DeckHand.
   public void insert(Card add)
   {
      //Note: This code was modified from CSC205 - Sample Stack Class - push() method
      if(_size >= _list.length)
      {
         Card[] temp = new Card[_list.length   FIXED];
         for(int i = 0; i < _size; i  )
         {
            temp[i] = _list[i];
         }
         _list = temp;
      }
      _list[_size] = add;
      _size  ;   
   }

/*
The delete Method will delete one instance of a Card with a given value from the DeckHand
and return the deleted instance.
@param givenValue: An integer representing a Value of a Card (E.X. - Ace, 2, 3, Jack, Queen King)
@return delteCard: The instance of the deleted Card
*/ 
   public Card delete(int givenValue)
   {
      int valueFound = 0;
      int suitFound = 0;
      int cardFound = 0;
      boolean notFound = true;  
      int i = 0;
      while(notFound)
      {
         if(givenValue == _list[i].getValue())
         {
            //Save i value to cardFound
            cardFound = i;
            valueFound = _list[i].getValue();
            suitFound = _list[i].getSuit();
            
            //Change Found to true so it exits the While Loop
            notFound = false;
         }
         i  ;
      }
      //Create a New Card that will be deleted
      Card deletedCard = new Card(suitFound, valueFound);
      
      //Now replace Card index with the lastCard and subtract one from size
      _list[cardFound] = _list[_size - 1];
      _size--;
      
      //Return DeletedCard
      return deletedCard;
   }
    
/*
The deleteAny Method will delete one instance of a Card selected at random from the DeckHand
and return the deleted instance.
@return delteCard: The instance of the deleted Card
*/ 
   public Card deleteAny()
   {
      //Randomly select a card from the DeckHand
      int randomCard = randomNumbers.nextInt(_size);
      Card deletedCard = _list[randomCard];
      
      //Replace Card index with the lastCard and subtract one from the size
      _list[randomCard] = _list[_size - 1];
      _size--;
      
      //Return the deleted instance of the Card
      return deletedCard;
   }
     
 

Комментарии:

1. Цикл никогда не выполняется. Измените инициализацию на true, затем при обнаружении установите false. Если вы не намеревались использовать while(!found) в цикле, но в любом случае убедитесь, что вы не можете попасть в ситуацию бесконечного цикла. (например, что остановит цикл, если ничего не найдено?)

2. @PaulT. Я сделал это, но я все равно получаю тот же результат — есть изображение, которое я прикрепил к своему сообщению. Спасибо за вашу помощь!

3. Затем обновите код вопроса для того, что было изменено. Мы не сможем запустить ваш пример без данных или остальной части класса. Попробуйте запустить пошаговый отладчик, чтобы проверить переменные, чтобы увидеть, что происходит, или, если вы еще не использовали его, добавьте несколько System.out.println(...) операторов внутри цикла для вывода значений, чтобы увидеть, что они содержат, тогда должно быть очевидно, какова может быть ситуация.

4. Код кажется неполным? … Отображаются ошибки: Card.getValue() is undefined , DeckHand.count() is undefined , и DeckHand.getSize() is undefined .

Ответ №1:

Похоже, что мой код работал, когда я вносил изменения благодаря @Paul T. и @ATP. Я скопировал свой код в другой файл, и он начал работать. Я действительно не знаю, в чем проблема.

Спасибо всем за вашу помощь!

-Рокки