2016-12-06 1 views
2

Во-первых, я не уверен, что я передал правильную проблему в названии этого вопроса, и если да, извините.java: Loop через два списка ArrayLists без ListIterators с использованием абстрактных типов данных

Моя проблема заключается в следующем: я использую список ADT для имитации выбора игры. Идея - это группа детей, которые сидят в кругу и поют рифму. Каждый ребенок говорит одно слово рифмы, пока рифма не будет завершена. Последний человек, который сказал рифму, вышел из игры. Затем рифма начинается с следующего ребенка. Последний оставшийся ребенок - победитель.

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

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

Это метод doRhyme().

Моя проблема до сих пор, когда я бегу, что у меня есть в коде, мое возвращение заключается в следующем:

Please enter the number of players 
(It should be an integer value greater than or equal to 2):5 
The players list is: 1 2 3 4 5 
Please enter a rhyme: 
One Two Three Four Five 
Player 1: One 
Player 2: Two 
Player 5: Three 
Player null: Four 
Player null: Five 
Rhyme performance error! 
The players list is: 5 

The winner is: 5 

Я использовал один два три четыре пять, как рифма просто проверить код из. Надеюсь, это никого не смущает.

Выходной код должен выглядеть следующим образом:

Please enter the number of players 
(It should be an integer value greater than or equal to 2):5 
The players list is: 1 2 3 4 5 
Please enter a rhyme: One Two Three Four Five 
Player 1: One 
Player 2: Two 
Player 3: Three 
Player 4: Four 
Player 5: Five 
Removing player 5 
The players list is: 1 2 3 4 

Player 1: One 
Player 2: Two 
Player 3: Three 
Player 4: Four 
Player 1: Five 
Removing player 1 
The players list is: 2 3 4 

and so on until only one player is left.... 

Включено вот код до сих пор. Любая помощь будет принята с благодарностью. Тем не менее, я буду продолжать вычислять правильный код.

public class RhymeGame 
    { 
     public static void main(String args[]) 
     { 
      ListInterface<Integer> players = null; 
      ListInterface<String> rhyme = null; 

      int max; 
      int position = 1; 

      max = getInt(); 
      players = new AList<Integer>(); 

      for(int i = 1; i <= max; i++) 
      { 
       players.add(i); 
      } 

      System.out.println("The players list is: " + players); 

      rhyme = getRhyme(); 

      while(players.getLength() > 1) 
      { 
       position = doRhyme(players, rhyme, position); 

       System.out.println("The players list is: " + players); 
       System.out.println(); 
      } 

      System.out.println("The winner is: " + players.getEntry(1)); 

     }//end of main 

     //Requires user to input the number of players. 
     private static int getInt() 
     { 
      Scanner input; 
      int result = 10;  //default value is 10 

      try 
      { 
       System.out.print("Please enter the number of players\n(It should be an integer value greater than or equal to 2):"); 
       input = new Scanner(System.in); 
       result = input.nextInt(); 
      } 
      catch(NumberFormatException e) 
      { 
       System.out.println("Could not convert input to an integer"); 
       System.out.println(e.getMessage()); 
       System.out.println("Will use 10 as the default value"); 
      }   
      catch(Exception e) 
      { 
       System.out.println("There was an error with System.in"); 
       System.out.println(e.getMessage()); 
       System.out.println("Will use 10 as the default value"); 
      } 

      return result; 

     }//end of getInt 

     //Requires user to input a rhyme 
     //(does not necessarily have to rhyme) 
     private static ListInterface<String> getRhyme() 
     { 
      Scanner input; 
      Scanner rhymeWords; 
      String inString; 

      ListInterface<String> rhyme = new AList<String>(); 

      try 
      { 
       input = new Scanner(System.in); 

       System.out.println("Please enter a rhyme:"); 

       inString = input.nextLine().trim(); 
       rhymeWords = new Scanner(inString); 

       while(rhymeWords.hasNext()) 
       { 
        rhyme.add(rhymeWords.next()); 
       } 
      } 
      catch(Exception e) 
      { 
       System.out.println("Input error!"); 
       System.out.println(e.getMessage()); 
       getRhyme(); 
      } 

      //At least one word in the rhyme 
      if(rhyme.getLength() < 1) 
      { 
       System.out.println("You must enter at least one word in the rhyme"); 
       getRhyme(); 
      } 

      return (ListInterface<String>)rhyme; 

     }//end of getRhyme 

     //Loops through the rhyme with the players in the list, 
     //removing the selected player at the end of the rhyme. 
     // 
     //players = the list holding the players 
     //rhyme = the list holding the words of the rhyme 
     //startAt = a position to start the rhyme at 
     // 
     //the position of the player eliminated will be returned. 
     public static int doRhyme(ListInterface<Integer> players, ListInterface<String> rhyme, int startAt) 
     { 
      int numPlayers; 

      try 
      { 
       numPlayers = players.getLength(); 

       while(numPlayers > 2) 
       { 
        for(startAt = 1; startAt < players.getLength(); startAt++) 
        { 
         for(startAt = 1; startAt < rhyme.getLength() + 1; startAt++) 
         { 
          System.out.println("Player " + players.getEntry(startAt) + ": " + rhyme.getEntry(startAt)); 
          numPlayers = players.remove(--numPlayers); 
         }     
        } 
       } 
      } 
      catch(Exception e) 
      { 
       System.out.println("Rhyme performance error!"); 
      } 

      return startAt; 

     }//end of doRhyme 

    }//end of class 

Интерфейс для списка следующий (на случай, если кто-то захочет увидеть методы, с которыми я должен работать).

/** 
     An interface for the ADT list. 
     Entries in the list have positions that begin with 1. 
    */ 
    public interface ListInterface<T> 
    { 

     /** Adds a new entry to the end of this list. 
      Entries currently in the list are unaffected. 
      The list's size is increased by 1. 
      @param newEntry the object to be added as a new entry */ 
     public void add(T newEntry); 

     /** Adds a new entry at a specified position within this list. 
      Entries originally at and above the specified position 
      are at the next higher position within the list. 
      The list's size is increased by 1. 
      @param newPosition an integer that specifies the desired 
           position of the new entry 
      @param newEntry the object to be added as a new entry 
      @return true if the addition is successful, or 
        false if newPosition < 1, or newPosition > getLength() + 1 */ 
     public boolean add(int newPosition, T newEntry); 

     /** Removes the entry at a given position from this list. 
      Entries originally at positions higher than the given 
      position are at the next lower position within the list, 
      and the list's size is decreased by 1. 
      @param givenPosition an integer that indicates the position of 
           the entry to be removed 
      @return a reference to the removed entry or null, if either 
        the list was empty, givenPosition < 1, or 
        givenPosition > getLength() */ 
     public T remove(int givenPosition); 

     /** Removes all entries from this list. */ 
     public void clear(); 

     /** Replaces the entry at a given position in this list. 
      @param givenPosition an integer that indicates the position of 
           the entry to be replaced 
      @param newEntry the object that will replace the entry at the 
          position givenPosition 
      @return true if the replacement occurs, or false if either the 
        list is empty, givenPosition < 1, or 
        givenPosition > getLength() */ 
     public boolean replace(int givenPosition, T newEntry); 

     /** Retrieves the entry at a given position in this list. 
      @param givenPosition an integer that indicates the position of 
           the desired entry 
      @return a reference to the indicated entry or null, if either 
        the list is empty, givenPosition < 1, or 
        givenPosition > getLength() */ 
     public T getEntry(int givenPosition); 

     /** Sees whether this list contains a given entry. 
      @param anEntry the object that is the desired entry 
      @return true if the list contains anEntry, or false if not */ 
     public boolean contains(T anEntry); 

     /** Gets the length of this list. 
      @return the integer number of entries currently in the list */ 
     public int getLength(); 

     /** Sees whether this list is empty. 
      @return true if the list is empty, or false if not */ 
     public boolean isEmpty(); 

     /** Retrieves all entries that are in this list in the order in which 
      they occur in the list. */ 
     public T[] toArray(); 
    } 

Определения ALIST заключаются в следующем:

/** 
     A class that implements the ADT list by using an array. 
     The list is unbounded. 
    */ 
    public class AList<T> implements ListInterface<T> 
    { 
     private T[] list; // array of list entries 
     private int numberOfEntries; 
     private static final int DEFAULT_INITIAL_CAPACITY = 25; 

     public AList() 
     { 
      this(DEFAULT_INITIAL_CAPACITY); 

     }//end of constructor 

     public AList(int initialCapacity) 
     { 
      numberOfEntries = 0; 
      T[] tempList = (T[])new Object[initialCapacity]; 
      list = tempList; 

     }//end of constructor 

     public void add(T newEntry) 
     { 
      boolean isSuccessful = true; 

      if(!isFull()) 
      { 
       //ensureCapacity(); 
       list[numberOfEntries] = newEntry; 
       numberOfEntries++; 
      } 
      else 
      { 
       isSuccessful = false; 
      } 

     }//end of add 

     public boolean add(int newPosition, T newEntry) 
     { 
      boolean isSuccessful = true; 

      if(!isFull() && (newPosition >= 1) && (newPosition <= numberOfEntries + 1)) 
      { 
       ensureCapacity(); 
       makeRoom(newPosition);    
       list[newPosition - 1] = newEntry; 
       numberOfEntries++; 
      } 
      else 
      { 
       isSuccessful = false; 
      } 

      return isSuccessful; 

     }//end of add overload 

     public T remove(int givenPosition) 
     {   
      T result = null; // return value 

      if((givenPosition >= 1) && (givenPosition <= numberOfEntries))            
      { 
       assert !isEmpty(); 

       result = list[givenPosition - 1]; // get entry to be removed 

       // move subsequent entries towards entry to be removed, 
       // unless it is last in list 
       if(givenPosition < numberOfEntries) 
       { 
        removeGap(givenPosition); 
       } 

       numberOfEntries--; 

      } // end if 

      return result; // return reference to removed entry, or 
      // null if either list is empty or givenPosition 
      // is invalid 

     }//end of remove 

     public void clear() 
     { 

      for(int index = 0; index < numberOfEntries; index++) 
      { 
       list[index] = null; 
      } 

      numberOfEntries = 0; 

     }//end of clear 

     public boolean replace(int givenPosition, T newEntry) 
     { 
      boolean isSuccessful = true; 

      if(!isFull() && (givenPosition >= 1) && (givenPosition <= numberOfEntries)) // test catches empty list 
      { 
       assert !isEmpty(); 
       list[givenPosition - 1] = newEntry; 
      } 
      else 
      { 
       isSuccessful = false; 
      } 

      return isSuccessful; 

     }//end of replace 

     public T getEntry(int givenPosition) 
     { 
      T result = null; // result to return 

      if((givenPosition >= 1) && (givenPosition <= numberOfEntries)) 
      { 
       assert !isEmpty(); 
       result = list[givenPosition - 1]; 
      } 

      return result; 

     }//end of getEntry 

     public boolean contains(T anEntry) 
     { 
      boolean found = false; 

      for(int index = 0; !found && (index < numberOfEntries); index++) 
      { 
       if(anEntry.equals(list[index])) 
       { 
        found = true; 
       } 
      } 

      return found; 

     }//end of contains 

     public int getLength() 
     { 
      return numberOfEntries; 

     }//end of getLength 

     public boolean isEmpty() 
     { 
      return numberOfEntries == 0; 

     }//end of isEmpty 

     public boolean isFull() 
     { 
      return numberOfEntries == list.length; 
     } 

     public T[] toArray() 
     { 
      T[] result = (T[])new Object[numberOfEntries]; 

      for(int index = 0; index < numberOfEntries; index++) 
      { 
       result[index] = list[index]; 
      } 

      return result; 

     }//end of toArray 

     public String toString() 
     // Returns a nicely formatted string that represents this list. 
     { 
      String listString = ""; 

      for(int i = 0; i < numberOfEntries; i++) 
      { 
       listString = listString + " " + list[i]; 
      } 

      return listString; 

     }//end of toString 

     // Doubles the size of the array list if it is full. 
     private void ensureCapacity() 
     { 
      if(numberOfEntries == list.length) 
      { 
       list = Arrays.copyOf(list, 2 * list.length); 
      } 

     }//end of ensureCapacity 

     // Makes room for a new entry at newPosition. 
     // Precondition: 1 <= newPosition <= numberOfEntries + 1; 
     //    numberOfEntries is list's length before addition. 

     private void makeRoom(int newPosition) 
     { 
      assert(newPosition >= 1) && (newPosition <= numberOfEntries + 1); 

      int newIndex = newPosition - 1; 
      int lastIndex = numberOfEntries - 1; 

      // move each entry to next higher index, starting at end of 
      // list and continuing until the entry at newIndex is moved 
      for(int index = lastIndex; index >= newIndex; index--) 
      { 
       list[index + 1] = list[index]; 
      } 

     }//end of makeRoom 

     // Shifts entries that are beyond the entry to be removed to the 
     // next lower position. 
     // Precondition: 1 <= givenPosition < numberOfEntries; 
     //    numberOfEntries is list's length before removal. 

     private void removeGap(int givenPosition) 
     { 
      assert(givenPosition >= 1) && (givenPosition < numberOfEntries); 

      int removedIndex = givenPosition - 1; 
      int lastIndex = numberOfEntries - 1; 

      for(int index = removedIndex; index < lastIndex; index++) 
      { 
       list[index] = list[index + 1]; 
      } 

     }//end of removeGap 

    }//end of class 
+0

Вы должны использовать эту строку в свой улов: 'System.out.println ("! Ошибка производительности Rhyme \ п" + e.getMessage());' 'или e.printStackTrace() '. А затем добавьте вывод здесь. – ChiefTwoPencils

+0

У меня это было изначально, но это только добавляет «нуль» ниже «ошибки производительности рифмы!». – Elekidcore

+0

ALIST не указан в коде, код нуждается в рефакторинге – firephil

ответ

1

Может быть, это поможет:
Я вижу, что есть два возможных случая:

Случай 1:
Размер списка рифм больше или равно размеру списка лиц.
Действие - удалить последний элемент в списке лиц.

Дело 2:
Размер персоны превышает список рифм.
Действие - удалить элемент в списке лицо, которое по адресу:
index = (person.size() % rhyme.size()) - 1

Ниже приведен пример кода для приложения:

public static void main(String[] args){ 

    //build lists and populate. Make sure that there are more 
    //players than rhymes so we can hit both cases. 
    ArrayList<Integer> player = new ArrayList<>(); 
    ArrayList<Integer> rhyme = new ArrayList<>(); 
    for(int i = 0; i < 10; i++){ 
     if(i < 6){ 
      rhyme.add(i); 
     } 
     player.add(i); 
    } 

    //play the game until we find a winner 
    while(player.size() > 1) { 

     int indexToRemove; 

     //case 1 followed by case 2 
     if (rhyme.size() >= player.size()) { 
      indexToRemove = player.size() - 1; 
     } else { 
      indexToRemove = (player.size() % rhyme.size()) - 1; 
     } 
     System.out.println(player.get(indexToRemove)); 
     player.remove(indexToRemove); 
    } 
    System.out.println(player); 
} 

Выход:

3 
2 
1 
0 
9 
8 
7 
6 
5 
[4] 
+0

Я думаю, что одна проблема, с которой я сталкиваюсь, заключается в том, что вместо двух целых массивов я имею один целочисленный arraylist и один массив Arraylist. Выход должен содержать оба. Вот пример: В круге: [Игрок 1, Игрок 2, Игрок 3, Игрок 4, Игрок 5, Игрок 6] Игрок 1 <- Eenie, Игрок 2 <- Meenie, Игрок 3 <- Mainee, Игрок 4 <- Mo Игрок 4 отсутствует! – Elekidcore

+0

Я не думаю, что тип 'ArrayList' имеет значение. Они представляют собой индексированные структуры данных независимо. Тип любого списка действительно не имеет значения, если вы представляете свои «Игроки» и «Раймы», как хотите. Вы можете создавать типы «Player» и «Rhyme» и по-прежнему использовать свойства размера каждого списка, чтобы решить, какой игрок должен быть удален. Также считайте, что каждый раз, когда игра воспроизводится, нет итерации. Таким образом, игра в одно время занимает постоянное время, а не повторение списка, который будет линейным временем относительно самого длинного списка. – Imposter

0

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

private static void runGame(String[] rhyme, List<String> players) { 
    System.out.println("Rhyme is " + Arrays.toString(rhyme)); 
    do { 
     System.out.println("The player list is " + players); 
     for (int i = 0; i < rhyme.length; i++) { 
      System.out.println(players.get(i % players.size()) + ": " + rhyme[i]); 
     } 
     System.out.println("Removing " + players.remove((rhyme.length - 1) % players.size())); 
    } while (players.size() > 1); 
    System.out.println("The winner is " + players.get(0)); 
} 

Выход:

Rhyme is [one, two, three, four, five] 
The player list is [Player 1, Player 2, Player 3, Player 4, Player 5] 
Player 1: one 
Player 2: two 
Player 3: three 
Player 4: four 
Player 5: five 
Removing Player 5 
The player list is [Player 1, Player 2, Player 3, Player 4] 
Player 1: one 
Player 2: two 
Player 3: three 
Player 4: four 
Player 1: five 
Removing Player 1 
The player list is [Player 2, Player 3, Player 4] 
Player 2: one 
Player 3: two 
Player 4: three 
Player 2: four 
Player 3: five 
Removing Player 3 
The player list is [Player 2, Player 4] 
Player 2: one 
Player 4: two 
Player 2: three 
Player 4: four 
Player 2: five 
Removing Player 2 
The winner is Player 4 
Смежные вопросы