lundi 16 novembre 2020

How to fix error "java.lang.IndexOutOfBoundsException: Index: 0, Size: 0"

I am writing a class called Deck to add all 52 cards in a deck to a LinkedList

import java.util.*;
import java.util.Random;

public class Deck{

  //Member variables
  private LinkedList<Card> cardList = new LinkedList<Card>();
  private int numOfCards;
  private String [] numbers = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
  private String [] suit = {"hearts","spades","clubs","diamonds"};
  //Random rand = new Random();

  //Constructor
  public Deck(){
    for (int s = 0; s < 3; s++){
      for (int n = 0; n < 13; n++){
        cardList.add(new Card(numbers[n],suit[s]));
      }
    }
    numOfCards = 52;
  }

  //Method
  // Deal method removes random card from list and returns that card

  public Card deal(){
    if (numOfCards > 0){
      int min = 0;
      int max = numOfCards;
      int randomNum = (int)Math.random() * (max - min +1) + min;
      numOfCards --;
      return cardList.remove(randomNum);
    } else{
      return null;
    }
  }

These are the errors I'm getting

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
        at java.util.LinkedList.checkElementIndex(LinkedList.java:555)
        at java.util.LinkedList.remove(LinkedList.java:525)
        at Deck.deal(Deck.java:39)
        at Game.<init>(Game.java:31)
        at Simulation.simulate(Simulation.java:45)
        at Main.main(Main.java:4)

It seems that all the errors from the other .java files point to the Deck class. How can I fix this runtime error? Thanks!

edit: This is my Main

public class Main{
  public static void main (String[] args){
    Simulation sim = new Simulation(Integer.parseInt(args[0]));
    sim.simulate();
  }
}

edit 2: This is Simulation. Line 45 is Game game = new Game(); For context, I am creating a card game similar to War but with a couple rule changes

import java.util.*;

public class Simulation{

  //Instance variables
  private int numOfGames;
  private int numOfBattles;
  private int numOfWars;
  private int numOfDoubleWars;
  LinkedList<Integer> individualBattles = new LinkedList<Integer>();
  LinkedList<Integer> individualWars = new LinkedList<Integer>();
  private double averageBattles;
  private double averageWars;
  private double averageDWars;
  private int greatestBattle;
  private int smallestBattle;
  private int greatestWar;
  private int smallestWar;

  //Constructor
  public Simulation(int numGames){
    numOfGames = numGames;
  }

  //Accessors and Mutators
  //Mutator
  public void setNumOfGames(int numGames){
    numOfGames = numGames;
  }
  //Accessor
  public int getNumOfGames(){
    return numOfGames;
  }

  //Methods
  public void simulate(){
    while (numOfGames > 0){
      Game game = new Game();
      game.play();
      individualBattles.add(game.getNumBattles());
      individualWars.add(game.getNumWars());
      numOfBattles = game.getNumBattles();
      numOfWars = game.getNumWars();
      numOfDoubleWars = game.getNumDoubleWars();
      numOfGames --;
    }
  }
  public void calculate(){
    //Average num of battles per Game
    averageBattles = numOfBattles/numOfGames;
    //Average num of wars per Game
    averageWars = numOfWars/numOfGames;
    //Average num of double wars per game
    averageDWars = numOfDoubleWars/numOfGames;
    //Max/min number of battles
    int greatestB = 0;
    int smallestB = 0;
    for (int i = 0; i < individualBattles.size(); i++){
      if (individualBattles.get(i) > greatestB) greatestB = individualBattles.get(i);
      else if (individualBattles.get(i) < smallestB) smallestB = individualBattles.get(i);
    }
    greatestBattle = greatestB;
    smallestBattle = smallestB;
    //Max/min number of wars
    int greatestW = 0;
    int smallestW = 0;
    for (int i = 0; i < individualWars.size(); i++){
      if (individualWars.get(i) > greatestW) greatestW = individualWars.get(i);
      else if (individualWars.get(i) < smallestW) smallestW = individualWars.get(i);
    }
    greatestWar = greatestW;
    smallestWar = smallestW;
  }

  public void report(){
    System.out.println("\nHere are your stats: " + "\nAverage number of battles: " + averageBattles +
    "\nAverage number of wars: " + averageWars + "\nAverage number of double wars: " + averageDWars +
    "\nMax number of battles per game: " + greatestBattle + "\nMin number of battles per game: " + smallestBattle +
    "\nMax number of wars per game: " + greatestWar + "\nMin number of Wars per game: " + smallestWar );
  }
}

edit 3: This is my Game. Line 31 is player2Cards.add(deck.deal());

import java.util.*;

public class Game{

  //Instance variables
  private Player player1;
  private Player player2;
  //game statistic variables
  private int numBattles;
  private int numWars;
  private int numDoubleWars;

  private Deck deck;
  private LinkedList<Card> player1Cards = new LinkedList<Card>();
  private LinkedList<Card> player2Cards = new LinkedList<Card>();
  private LinkedList<Card> table = new LinkedList<Card>();

  //Default Constructor
  public Game(){
    Deck deck = new Deck();

    for (int i = 0; i < 51; i++){
      player1Cards.add(deck.deal());
      player2Cards.add(deck.deal());
    }
    player1 = new Player(1,player1Cards);
    player2 = new Player(2,player2Cards);
  }
  // Accessors and Mutators
  //Accessors
  public Player getPlayer1(){
    return player1;
  }
  public Player getPlayer2(){
    return player2;
  }
  //Mutator
  public void setNumBattles(int battlesNum){
    numBattles = battlesNum;
  }
  //Accessor
  public int getNumBattles(){
    return numBattles;
  }
  //Mutator
  public void setNumWars(int warsNum){
    numWars = warsNum;
  }
  //Accessor
  public int getNumWars(){
    return numWars;
  }
  //Mutator
  public void setNumDoubleWars(int warDouble){
    numDoubleWars = warDouble;
  }
  //Accessor
  public int getNumDoubleWars(){
    return numDoubleWars;
  }


  //Methods
  // Method to compute median
  static double median(int[] values) {
     Arrays.sort(values);
     double median;
     int totalValues = values.length;
     if (totalValues % 2 == 0) {
        int sumOfMiddleValues = values[totalValues / 2] + values[totalValues / 2 - 1];
        median = ((double) sumOfMiddleValues) / 2;
     } else {
        median = (double) values[values.length / 2];
  }
  return median;
 }

  // Converts String values to int
  public int translator(Card card){
    int value = 0;
    if (card.getNum() == "A") value = 14;
    if (card.getNum() == "K") value = 13;
    if (card.getNum() == "Q") value = 12;
    if (card.getNum() == "J") value = 11;
    if (card.getNum() == "10") value = 10;
    if (card.getNum() == "9") value = 9;
    if (card.getNum() == "8") value = 8;
    if (card.getNum() == "7") value = 7;
    if (card.getNum() == "6") value = 6;
    if (card.getNum() == "5") value = 5;
    if (card.getNum() == "4") value = 4;
    if (card.getNum() == "3") value = 3;
    if (card.getNum() == "2") value = 2;
    return value;
  }

// Play method carries out the game
  public void play(){

    while (player1.hasWon() == false && player2.hasWon() == false){
      for (int i = 0; i < 3; i++){
        Card p1_flip1 = player1.flip();
        Card p1_flip2 = player1.flip();
        Card p1_flip3 = player1.flip();
        Card p2_flip1 = player2.flip();
        Card p2_flip2 = player2.flip();
        Card p2_flip3 = player2.flip();

        table.add(p1_flip1);
        System.out.println("Player 1 flipped: " + p1_flip1.getNum());
        table.add(p1_flip2);
        System.out.println("Player 1 flipped: " + p1_flip1.getNum());
        table.add(p1_flip3);
        System.out.println("Player 1 flipped: " + p1_flip1.getNum());
        table.add(p2_flip1);
        System.out.println("Player 2 flipped: " + p1_flip1.getNum());
        table.add(p2_flip2);
        System.out.println("Player 2 flipped: " + p1_flip1.getNum());
        table.add(p2_flip3);
        System.out.println("Player 2 flipped: " + p1_flip1.getNum());

        int p1flip1 = translator(p1_flip1);
        int p1flip2 = translator(p1_flip2);
        int p1flip3 = translator(p1_flip3);
        int p2flip1 = translator(p2_flip1);
        int p2flip2 = translator(p2_flip2);
        int p2flip3 = translator(p2_flip3);

        int[] player1Array = {p1flip1, p1flip2, p1flip3};
        int[] player2Array = {p2flip1, p2flip2, p2flip3};

        if (median(player1Array) > median(player2Array)){
          System.out.println("Player 1 wins this round!");
          player1.collect(table);
        } else if (median(player1Array) < median(player2Array)){
          System.out.println("Player 2 wins this round!");
          player2.collect(table);

          // War in play method
        } else {
          int warCounter = 0;
          System.out.println("It's war hours.");
          int warCard1 = 0;
          int warCard2 = 0;
          int doubleCounter = 0;
          while (warCard1 == warCard2){
            Card oneWarCard = player1.flip();
            Card twoWarCard = player2.flip();
            table.add(oneWarCard);
            table.add(twoWarCard);
            warCard1 = translator(oneWarCard);
            warCard2 = translator(twoWarCard);
            warCounter ++;
          }
          if (warCounter == 2){
            numDoubleWars ++;
            warCounter = 0;
          }
          if (warCard1 > warCard2) {
            System.out.println("Player 1 wins this round!");
            player1.collect(table);
          }
          else if (warCard2 > warCard1) player2.collect(table);{
            System.out.println("Player 2 wins this round!");
          }
          numWars ++;
        }
      }
      numBattles ++;
    }
    if (player1.hasWon()) System.out.println("Player 1 has won!");
    else System.out.println("Player 2 has won!");
  }
}



Aucun commentaire:

Enregistrer un commentaire