CardPile Index Out of bounds - java

I'm currently trying to convert my code to ArrayList and I can't seem to make it work. I'm running the whole program and it tells me Index out bounds. I'm sure I forgot to add the size of the array for the cards, but I don't know how to add it. Thanks for the help!
Edit: The error I get is at the bottom. Also, it tells me to go to the removeTop method. It looks fine there.
import java.util.Random;
import java.util.List;
import java.util.ArrayList;
public class CardPile {
private ArrayList<Card> cards = new ArrayList<Card>();
private static Random r = new Random(1);
public void addToBottom(Card c) {
if (this.cards.size() == 52) {
System.out.println("The CardPile is full. You cannot add any more Card objects.");
}
this.cards.add(c);
}
public Card removeCard(Card c) {
if (this.cards.contains(c)) {
this.cards.remove(c);
}
return null;
}
public Card removeTop() {
return this.cards.remove(0);
}
public int searchValue(int value) {
int count = 0,
for (int i = 0;i < this.cards.size();i++) {
if (this.cards.get(i).getValue() == value) {
count++;
}
}
//System.out.println("Count = "+count);
return count;
}
public Card[] removeAll(int value)
//System.out.println("(removeAll) cards ="+ cards);
int count = searchValue(value);
Card[] removed = new Card[count];
int deletedCount = 0;
int i = 0;
while (deletedCount < count) {
if (this.cards.get(i).getValue() == value) {
removed[deletedCount] = this.cards.remove(i);
deletedCount++;
} else {
i++;
}
}
return removed;
}
public int getNumberCards() {
return this.cards.size();
}
public String toString() {
if (this.cards.isEmpty()) {
return "";
}
String builder = "";
for (int i = 0;i < this.cards.size() - 1;i++) {
builder = builder + this.cards.get(i) + ", ";
}
builder = builder + this.cards.get(this.cards.size() - 1);
return builder;
}
public void shuffle() {
if (this.cards.isEmpty()) {
return;
}
for (int count = 0; count < 100000;count++) {
int i = r.nextInt(this.cards.size());
int j = r.nextInt(this.cards.size());
Card temp = this.cards.get(i);
this.cards.set(i, this.cards.get(j));
this.cards.set(j, temp);
}
}
public static CardPile makeFullDeck() {
CardPile deck = new CardPile();
for (int suit = 0;suit < 4;suit++) {
for (int value = 1; value <= 13;value++) {
deck.addToBottom(new Card(suit, value));
}
}
deck.shuffle();
return deck;
}
}
**Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.remove(ArrayList.java:492)
at CardPile.removeTop(CardPile.java:40)
at GoFish.dealCards(GoFish.java:112)
at GoFish.main(GoFish.java:13)**
EDIT:
This is the Player class:
public class Player {
private boolean[] books;
private CardPile pile;
private static int MAXIMUM_VALUE_CARD = 13;
public Player()
{
this.pile = new CardPile();
this.books = new boolean[13]; //by default all are false
}
public boolean hasCard(int value)
{
return this.pile.searchValue(value) > 0;
}
public Card[] removeAll(int value)
{
return this.pile.removeAll(value);
}
public void addAll(Card[] cards)
{
for (int i = 0; i < cards.length; i++)
{
this.pile.addToBottom(cards[i]);
}
}
//optional additional method
public void addCard(Card card)
{
this.pile.addToBottom(card);
}
public int getNumberCards()
{
return this.pile.getNumberCards();
}
public int countBooks()
{
int count = 0;
for (int i = 0; i < MAXIMUM_VALUE_CARD; i++)
{
if (books[i])
{
count++;
}
}
return count;
}
public void addBook(int value)
{
this.books[value - 1] = true;
}
public void printHand()
{
System.out.println("Player's hand is " + this.pile);
}
}
And this is the GoFish class:
import java.util.Scanner;
public class GoFish {
private static Scanner reader;
public static void main(String[] args)
{
System.out.println("How many players?");
reader = new Scanner(System.in);
int numberPlayers = reader.nextInt();
Player[] players = createPlayersArray(numberPlayers);
int currentTurn = 0;
CardPile deck = CardPile.makeFullDeck();
dealCards(deck, players);
int maximumRetries = 2;
int numRetries = 0;
while(deck.getNumberCards() > 0 && players[currentTurn].getNumberCards() > 0)
{
updateBooks(players[currentTurn]);
if (numRetries == maximumRetries)
{
numRetries = 0;
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
System.out.println("Player " + currentTurn + ", here is your hand. What card would you like to ask for?");
players[currentTurn].printHand();
int queryCard = reader.nextInt();
System.out.println("And from whom would you like to get it from?");
int queryPlayer = reader.nextInt();
if (queryCard < 1 || queryCard > 13 || queryPlayer < 0 || queryPlayer >= numberPlayers || queryPlayer == currentTurn)
{
System.out.println("Invalid entries. Please retry");
numRetries++;
}
else
{
numRetries = 0;
boolean hasCard = players[queryPlayer].hasCard(queryCard);
if (hasCard)
{
System.out.println("Cards found!");
Card[] removed = players[queryPlayer].removeAll(queryCard);
players[currentTurn].addAll(removed);
}
else
{
System.out.println("Go fish!");
Card top = deck.removeTop();
System.out.println("You drew " + top);
players[currentTurn].addCard(top);
//check to make sure this extra card didn't form a book
//Note this could happen even if it doesn't match the card they were asking about
updateBooks(players[currentTurn]);
if (top.getValue() == queryCard)
{
System.out.println("You successfully went fishing!");
}
else
{
currentTurn++;
if (currentTurn == numberPlayers)
{
currentTurn = 0;
}
}
}
}
}
//calculate the winner now
int maxPlayer = 0;
int maxPlayerBooks = players[0].countBooks();
for (int i = 1; i < numberPlayers; i++)
{
int currentBooks = players[i].countBooks();
if (currentBooks > maxPlayerBooks)
{
maxPlayer = i;
maxPlayerBooks = currentBooks;
}
}
System.out.println("Congratulations! Player " + maxPlayer + " you have won the game by accumulating " + maxPlayerBooks + " books!");
}
private static Player[] createPlayersArray(int numPlayers)
{
Player[] players = new Player[numPlayers];
for (int i = 0; i < numPlayers; i++)
{
players[i] = new Player();
}
return players;
}
private static void dealCards(CardPile deck, Player[] players)
{
final int NUMBER_CARDS_PER_PLAYER = 7;
for (int i = 0; i < NUMBER_CARDS_PER_PLAYER * players.length; i++)
{
Card next = deck.removeTop();
players[i % players.length].addCard(next);
}
}
private static void updateBooks(Player player)
{
for (int i = 1; i <= 13; i++)
{
//alternative option would be to modify the hasCard method to return an int instead of boolean. Then we could just count (this is probably better design)
Card[] valued = player.removeAll(i);
if (valued.length == 4)
{
player.addBook(i);
}
else
{
player.addAll(valued);
}
}
}
}

Related

How to keep BestScores in a File JAVA

I developed a game and I want to keep track of the Top-3 Best Scores in a file, so that we don't lose the Scores after closing the game. It's not working properly and I don't know why.
- The Best Scores are Integers, and the lowest it is the better. The Best Score is the lowest.
- It is not saving the Scores in ascending Order
It does create a file and it appears to work with the main tests but after a few Scores being add, it does not sort the array in ascending order, so the file is in the wrong way.
package pt.iscte.dcti.poo.sokoban.starter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
import pt.iul.ista.poo.utils.Point2D;
public class BestScores {
public int[] bestScore = new int[3];
public final int level;
public BestScores(int level) {
this.level = level;
}
public int[] getBestScore() {
return bestScore;
}
//Register BestScores
public void setBestScore(int score) {
for(int i = 0; i < bestScore.length; i++) {
if(bestScore[i] == 0) {
bestScore[i] = score;
return;
}
}
Arrays.sort(bestScore);
for (int i = 0; i < bestScore.length-1; i++) {
if(bestScore[i] == 0) {
int box1 = bestScore[i];
bestScore[i] = bestScore[i+1];
bestScore[i+1] = box1;
}
}
addBestScore(score);
}
public void addBestScore(int score) {
if(score < bestScore[bestScore.length - 1])
bestScore[bestScore.length - 1] = score;
Arrays.sort(bestScore);
for (int i = 0; i < bestScore.length-1; i++) {
if(bestScore[i] == 0) {
int box1 = bestScore[i];
bestScore[i] = bestScore[i+1];
bestScore[i+1] = box1;
}
}
}
public int getTopOne() {
return bestScore[0];
}
public int getLevel() {
return level;
}
//Check if the file exists, else create it
public void searchFile() {
File tmpDir = new File("bestScores/BestScore_" + level + ".txt");
if (!tmpDir.exists())
createOrAddScore();
else {
checkScores(tmpDir);
createOrAddScore();
}
}
//Create file with Scores if they exist.
public void createOrAddScore() {
try {
PrintWriter writer = new PrintWriter(new File("bestScores/BestScore_" + level + ".txt"));
writer.println("BestScores: ************Level:" + level + "************");
for(int i = 0; i < bestScore.length; i++) {
if(bestScore[i] != 0)
writer.println((i+1) + "º " + bestScore[i] + " " + "moves.");
}
writer.close();
}
catch (FileNotFoundException e) {
System.err.println("problema a escrever o ficheiro");
}
}
//Read File and return Best Scores, so that we don't lose the bestScores even after closing the game :D.
public void checkScores(File file) {
int[] array = new int[3];
try {
Scanner scanner = new Scanner(file);
String title_line = scanner.nextLine();
int i = 0;
while(scanner.hasNextLine()) {
String[] line = scanner.nextLine().split(" ");
array[i] = Integer.parseInt(line[1]);
i++;
}
}
catch (FileNotFoundException e) {
System.err.println("problema a escrever o ficheiro");
}
for (int i = 0; i < array.length; i++)
if(array[i] != 0)
setBestScore(array[i]);
}
public static void main(String[] args) {
// BestScores bS = new BestScores(4);
//test1 No BEstScores
// bS.searchFile();
//test2 WithBestScores
// bS.setBestScore(40);
// bS.setBestScore(15);
bS.setBestScore(50);
// bS.setBestScore(30);
// bS.setBestScore(10);
// bS.searchFile();
// int[] test = bS.getBestScore();
// for(int i = 0; i < test.length; i++)
// System.out.println(test[i]);
//test3 With file with Scores
// bS.searchFile();
// int[] test = bS.getBestScore();
// for(int i = 0; i < test.length; i++)
// System.out.println(test[i]);
}
}

How to fill a 2d array given values in another class

EDIT: THERE IS NOTHING ABOUT NULL POINTER. NOT A DUPLICATE -The Null pointer exception is what I get so I know I'm not filling the array right, that's what I'm asking. How do I fill the array?
I am trying to input the values inside of one class into the 2d array declared into another class.
The way it's supposed to work is in the main the nested loop is supposed to supply the values to the other method which is then supposed to input them into the 2d array.
Thanks
Here is main
public class Lab1 {
static final int NBPLAYERS = 11;
static final int NBMONTHS = 6;
public static void main(String[] args) {
String[] month = {"April", "May","June", "July", "August","September"};
String[] players ={"Colabello","Donaldson","Smoak","Martin","Goins","Encarnacion","Carrera","Tulow itzki","Pillar","Bautista","Travis"};
double[][] battingAvg = {
{0,.368,.300,.224,.386,.268},
{.319,.306,.269,.287,.324,.296},
{.229,.310,.213,.191,.203,.262},
{.197,.327,.239,.256,.138,.213},
{.276,.236,.172,.240,.314,.279},
{.205,.225,.303,.241,.407,.279},
{0,.302,.282,.244,.333,.231},
{0,0,0,.357,.214,.237},
{.273,.181,365,.283,.240,.323},
{.164,.295,.226,.219,.286,.293},
{.325,.189,.313,.368,0,0}};
double [][] onBase = {
{.417,.330,.286,.413,.362,.429},
{.370,.373,.322,.370,.408,.403},
{.372,.333,.275,.283,.243,.324},
{.367,.362,.329,.322,.263,.300},
{.323,.278,.221,.286,.442,.347},
{.258,.333,.382,.384,.460,.411},
{0,.357,.333,.277,.333,.313},
{0,0,0,.400,.325,.250},
{.297,.237,.380,.323,.283,.363},
{.325,.418,.388,.300,.370,.436},
{.393,.246,.313,.421,0,0}};
PlayerStats player;
BlueJays team = new BlueJays(NBPLAYERS, NBMONTHS);
for(int iPlayer=0; iPlayer<NBPLAYERS; iPlayer++) {
for(int iMonth=0; iMonth<NBMONTHS; iMonth++) {
player = new PlayerStats(players[iPlayer], iMonth, battingAvg[iPlayer][iMonth],onBase[iPlayer][iMonth]);
team.setPlayerStatsCell(player,iPlayer,iMonth);
}
}
team.getHighestSingleMonthBattingAvg();
team.getHighestOnBase(5);
team.getLowestBattingAvg(5);
team.getBestMonth("Bautista");
team.getBestOverallRecord();
team.getLowestOnBase();
The part of this method that I am trying to use ATM is the
PlayerStats setPlayerStatsCell(PlayerStats p, int nbPlayers, int nmMonths)
Which should, take the information from main and put it into the 2d array.
class BlueJays {
int nbPlayers;
int nbMonths;
int j = 0;
int highestBattingAvg;
int highestBattingMonth;
String highestBattingPlayer;
int highestOnBase;
int lowestAvg;
String lowestAvgPlayer;
int highestOverall;
String highestOverallPlayer;
int lowestOnBase;
int lowestOnBaseMonth;
String highestOnBasePlayer;
double bestOverAllMonth;
PlayerStats[][] stats;
public BlueJays(int nbplayers2, int nbmonths2) {
this.nbPlayers = nbplayers2;
this.nbMonths = nbmonths2;
this.stats = new PlayerStats[nbPlayers][nbMonths];
}
PlayerStats setPlayerStatsCell(PlayerStats p, int nbPlayers, int nmMonths) {
for(int i=0; i<nbPlayers; i++) {
for(int j=0; j<nmMonths; j++) {
stats[i][j]= p;
}
}
return p;
}
PlayerStats getHighestSingleMonthBattingAvg() {
j = 0;
for(int i = 0; i < nbPlayers; i++) {
for(j = 0; j<nbMonths; j++) {
stats[i][j].getAvg();
if(highestBattingAvg < stats[i][j].getAvg()) {
highestBattingMonth = stats[i][j].getMonth();
highestBattingPlayer = stats[i][j].getName();
}
System.out.println("Highest average batting player for the month " + highestBattingMonth + " is " + highestBattingPlayer);
}
}
return null;
}
PlayerStats getHighestOnBase(int month) {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][month].getOnBase();
if(highestOnBase < stats[i][month].getOnBase()) {
highestOnBasePlayer = stats[i][month].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
System.out.println("Highest average onBase player for the month " + month + highestOnBasePlayer);
}
}
return null;
}
public PlayerStats getLowestBattingAvg(int month) {
j = 0;
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][month].getOnBase();
if(lowestAvg > stats[i][month].getAvg()) {
lowestAvgPlayer = stats[i][month].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
}
System.out.println("Lowest average batting player for the month " + month + " is " + lowestAvgPlayer);
}
return null;
}
PlayerStats getBestMonth(String player) {
j = 0;
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getBoth();
if(bestOverAllMonth > stats[i][j].getAvg() && stats[i][j].getName().contains(player)) {
bestOverAllMonth = stats[i][j].getBoth();
}
if (i == nbMonths) {
j++;
i = 0;
}
}
System.out.println("Best month for the player " + player + " is " + bestOverAllMonth);
}
return null;
}
public String getBestOverallRecord() {
j = 0;
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getBoth();
if(highestOverall < stats[i][j].getBoth()) {
highestOverallPlayer = stats[i][j].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
}
System.out.println("Highest overall record is " + highestOverallPlayer);
}
return null;
}
public PlayerStats getLowestOnBase() {
j = 0;
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getOnBase();
if(lowestOnBase > stats[i][j].getOnBase()) {
double lowestOnBase = stats[i][j].getOnBase();
if(lowestOnBase > 0) {
lowestAvgPlayer = stats[i][j].getName();
} else {
i++;
}
if (i == nbMonths) {
j++;
i = 0;
}
}
}
System.out.println("Lowest On Base is " + lowestOnBase);
}
return null;
}
}
Here's the PlayerStats code
class PlayerStats {
private String name;
private int month;
private double battAvg, onBase;
public PlayerStats(String name, int month, double battingAvg, double onBase2) {
this.name = name;
this.month = month;
this.battAvg = battingAvg;
this.onBase = onBase2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public double getAvg() {
return battAvg;
}
public double getOnBase() {
return onBase;
}
public double getBoth() {
return battAvg + onBase;
}
}
And the exception it throws is a Null Pointer, which the array is not filling.
Exception in thread "main" java.lang.NullPointerException
at BlueJays.getHighestSingleMonthBattingAvg(BlueJays.java:52)
at Lab1.main(Lab1.java:52)
Highest average batting player for the month 0 is null
Highest average batting player for the month 0 is null
Highest average batting player for the month 0 is null
Highest average batting player for the month 0 is null
Highest average batting player for the month 0 is null
Your setPlayerStatsCell function makes no sense in context. Try this one:
PlayerStats setPlayerStatsCell(PlayerStats p, int nbPlayer, int nmMonth)
{
stats[nbPlayer][nmMonth] = p;
return p;
}
The error was caused by the old one not being able to set the last row and column of the table.

Java 2 dimensional array throwing out of bounds

I'm new with arrays.
This program i have created is throwing an out of bounds error with every method inside of the BlueJays class.
To be honest, im not even sure if im searching through the array right. Any help would be appreciated.
Thanks
This is my main
public class Lab1 {
static final int NBPLAYERS = 11;
static final int NBMONTHS = 6;
public static void main(String[] args) {
String[] month = {"April", "May","June", "July", "August","September"};
String[] players = {"Colabello","Donaldson","Smoak","Martin","Goins","Encarnacion","Carrera","Tulowitzki","Pillar","Bautista","Travis"};
double[][] battingAvg = {
{0,.368,.300,.224,.386,.268},
{.319,.306,.269,.287,.324,.296},
{.229,.310,.213,.191,.203,.262},
{.197,.327,.239,.256,.138,.213},
{.276,.236,.172,.240,.314,.279},
{.205,.225,.303,.241,.407,.279},
{0,.302,.282,.244,.333,.231},
{0,0,0,.357,.214,.237},
{.273,.181,365,.283,.240,.323},
{.164,.295,.226,.219,.286,.293},
{.325,.189,.313,.368,0,0}};
double [][] onBase = {
{.417,.330,.286,.413,.362,.429},
{.370,.373,.322,.370,.408,.403},
{.372,.333,.275,.283,.243,.324},
{.367,.362,.329,.322,.263,.300},
{.323,.278,.221,.286,.442,.347},
{.258,.333,.382,.384,.460,.411},
{0,.357,.333,.277,.333,.313},
{0,0,0,.400,.325,.250},
{.297,.237,.380,.323,.283,.363},
{.325,.418,.388,.300,.370,.436},
{.393,.246,.313,.421,0,0}};
PlayerStats Player;
BlueJays team = new BlueJays(NBPLAYERS, NBMONTHS);
team.getHighestSingleMonthBattingAvg();
team.getHighestOnBase(5);
team.getLowestBattingAvg(6);
team.getBestMonth("Bautista");
team.getBestOverallRecord();
team.getLowestOnBase();
}
}
This is my PlayerStats which has accessor/mutator methods.
class PlayerStats {
private String name;
private int month;
private double battAvg, onBase;
public PlayerStats(String name, int month, double battingAvg, double onBase2) {
this.name = name;
this.month = month;
this.battAvg = battingAvg;
this.onBase = onBase2;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public double getAvg() {
return battAvg;
}
public double getOnBase() {
return onBase;
}
public double getBoth() {
return battAvg + onBase;
}
}
And this is the class where the 2d array is created.
class BlueJays {
int nbPlayers;
int nbMonths;
int j = 0;
int highestBattingAvg;
int highestBattingMonth;
String highestBattingPlayer;
int highestOnBase;
int lowestAvg;
String lowestAvgPlayer;
int highestOverall;
String highestOverallPlayer;
int lowestOnBase;
int lowestOnBaseMonth;
String highestOnBasePlayer;
double bestOverAllMonth;
public BlueJays(int nbplayers2, int nbmonths2) {
this.nbPlayers = nbplayers2;
this.nbMonths = nbmonths2;
}
PlayerStats[][] stats = new PlayerStats[nbPlayers][nbMonths];
PlayerStats setPlayerStatsCell(PlayerStats player, int iPlayer, int iMonth) {
return player;
}
PlayerStats getHighestSingleMonthBattingAvg() {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getAvg();
if(highestBattingAvg < stats[i][j].getAvg()) {
highestBattingMonth = stats[i][j].getMonth();
highestBattingPlayer = stats[i][j].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
System.out.println("Highest average batting player for the month " + highestBattingMonth + " is " + highestBattingPlayer);
}
}
return null;
}
PlayerStats getHighestOnBase(int month) {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][month].getOnBase();
if(highestOnBase < stats[i][month].getOnBase()) {
highestOnBasePlayer = stats[i][month].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
System.out.println("Highest average onBase player for the month " + month + highestOnBasePlayer);
}
}
return null;
}
public PlayerStats getLowestBattingAvg(int month) {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][month].getOnBase();
if(lowestAvg > stats[i][month].getAvg()) {
lowestAvgPlayer = stats[i][month].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
System.out.println("Lowest average batting player for the month " + month + " is " + lowestAvgPlayer);
}
}
return null;
}
PlayerStats getBestMonth(String player) {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getBoth();
if(bestOverAllMonth > stats[i][j].getAvg() && stats[i][j].getName().contains(player)) {
bestOverAllMonth = stats[i][j].getBoth();
}
if (i == nbMonths) {
j++;
i = 0;
}
System.out.println("Best month for the player " + player + " is " + bestOverAllMonth);
}
}
return null;
}
public String getBestOverallRecord() {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getBoth();
if(highestOverall < stats[i][j].getBoth()) {
highestOverallPlayer = stats[i][j].getName();
}
if (i == nbMonths) {
j++;
i = 0;
}
System.out.println("Highest overall record is " + highestOverallPlayer);
}
}
return null;
}
public PlayerStats getLowestOnBase() {
while(j < nbMonths) {
for(int i = 0; i < nbPlayers; i++) {
stats[i][j].getOnBase();
if(lowestOnBase > stats[i][j].getOnBase()) {
double lowestOnBase = stats[i][j].getOnBase();
if(lowestOnBase > 0) {
lowestAvgPlayer = stats[i][j].getName();
} else {
i++;
}
if (i == nbMonths) {
j++;
i = 0;
}
}
System.out.println("Lowest On Base is " + lowestOnBase);
}
}
return null;
}
}
Here is the exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at BlueJays.getHighestSingleMonthBattingAvg(BlueJays.java:42)
at Lab1.main(JonathanRoy_Lab1.java:40)
Your problem may lay here:
// ... lots of other stuff
public BlueJays(int nbplayers2, int nbmonths2) {
this.nbPlayers = nbplayers2;
this.nbMonths = nbmonths2;
}
PlayerStats[][] stats = new PlayerStats[nbPlayers][nbMonths];
If you initialize an instance of your BlueJay-class it will create the array before you set the values nbPlayers and nbMonths. So you'll have an array of the size 0 and 0.
To avoid this you have to do following:
// ... lots of other stuff
public BlueJays(int nbPlayers, int nbMonths) {
this.nbPlayers = nbPlayers;
this.nbMonths = nbMonths;
// doesn't matter if you take the parameters or fields
this.stats = new PlayerStats[nbPlayers][nbMonths];
}
Hope I helped you out :)
I don't know what the exception is but here's what I got by scanning through your code.
You never reset j so most of your function calls won't make it past the first comparison.
The function call team.getLowestBattingAvg(6); uses the index 6, but since nbMonths=6, the highest index you can use is 5 (the indices go from 0 to 5 inclusive).

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError occurs

I am trying to make a game which breaks the tile when I type a specific key.
Firstly, here is what the exception.
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:77)
at sun.nio.cs.UTF_8.access$200(UTF_8.java:57)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:636)
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:691)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:579)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.PrintStream.newLine(PrintStream.java:545)
at java.io.PrintStream.println(PrintStream.java:807)
at code.gui.NewView.addTileToDelete(NewView.java:192)
at code.gui.NewView.deleteTileByColor(NewView.java:151)
at code.gui.NewView.deleteTileByColor(NewView.java:158)
at code.gui.NewView.deleteTileByColor(NewView.java:152)
It runs fine if I execute deleteTileByColor method once,
however from the second time, above error occurs.
Here's the code for game.
package code.gui;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import code.handlers.PressKeyHandler;
import code.model.DataModel;
import code.parts.GamePanel;
import code.parts.GameTile;
public class NewView extends JFrame {
int _exitCounter;
int _tileDeleteCounter;
int _column = 4;
int _row = 4;
GamePanel _gamePanel;
DataModel _dm;
GameTile _tile;
ArrayList<ArrayList<GameTile>> _gameTileList = new ArrayList<ArrayList<GameTile>>();
ArrayList<GamePanel> _gamePanLst = new ArrayList<GamePanel>();
ArrayList<Character> _letterList;
public NewView(DataModel dm) {
super("Sequence Game");
this._dm = dm;
setLayout(new GridLayout(1, 4));
shuffleLetter();
for (int i = 0; i < _column; i++) {
_gamePanel = new GamePanel();
System.out.println("1. _gameTileList에 new ArrayList 총 " + i + "개 추가");
for (int j = 0; j < _row; j++) {
_tile = new GameTile(_letterList.get((4 * i) + j));
_gamePanel.add(_tile);
_tile.addKeyListener(new PressKeyHandler(_dm));
}
_gamePanLst.add(_gamePanel);
}
System.out.println("어레이 리스트<어레이리스트> 사이즈 : " + _gameTileList.size());
setFrame();
this.setSize(300, 500);
this.setVisible(true);
this.add(_gamePanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
_dm.setView(this);
}
public void setFrame() {
for (int i = 0; i < _gamePanLst.size(); i++) {
this.add(_gamePanLst.get(i), i);
}
this.repaint();
this.revalidate();
}
public void update(char letter) {
resetTileArrLst();
Color tileColor;
for (int i = 0; i < _column; i++) {
for (int j = 0; j < _row; j++) {
if (_gamePanLst.get(i).getComponent(j).getName().equals("" + letter)) {
System.out.println("i : " + i + " / j : " + j);
// System.out.println("최초비교");
tileColor = setTileColor(_gamePanLst.get(i).getComponent(j));
addTileToDelete(i, j);
deleteTileByColor(i, j, tileColor);
}
}
}
checkToQuit();
setFrame();
}
public void shuffleLetter() {
ArrayList<Character> temp = new ArrayList<Character>();
int numOfLetters = 26;
for (int i = 0; i < numOfLetters; i++) {
temp.add((char) (97 + (i)));
}
Collections.shuffle(temp);
_letterList = temp;
}
public Color setTileColor(Component comp) {
System.out.println("**********setTileColor********** ");
System.out.println("compo color : " + comp.getBackground());
Color temp;
if (comp.getBackground().equals(Color.RED)) {
temp = Color.RED;
} else if (comp.getBackground().equals(Color.BLUE)) {
temp = Color.BLUE;
} else if (comp.getBackground().equals(Color.YELLOW)) {
temp = Color.YELLOW;
} else {
temp = Color.GREEN;
}
return temp;
}
public GameTile getEmptyTile() {
GameTile emptyTile = new GameTile(' ');
emptyTile.setBorder(BorderFactory.createEmptyBorder());
emptyTile.setBackground(Color.BLACK);
emptyTile.addKeyListener(new PressKeyHandler(_dm));
return emptyTile;
}
public void checkToQuit() {
int counter = 0;
for (int i = 0; i < _gamePanel.getComponentCount(); i++) {
if (_gamePanel.getComponent(i).getBackground() == Color.BLACK) {
counter++;
}
}
if (counter == _gamePanel.getComponentCount()) {
this.dispose();
}
}
public void deleteTile(int i) {
_gamePanel.remove(i);
_gamePanel.add(getEmptyTile(), i);
}
public void deleteTileByColor(int column, int row, Color tileColor) {
// Right
if (((column + 1) < 4) && tileColor == (_gamePanLst.get((column + 1)).getComponent(row).getBackground())) {
column = column + 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
// Left
if ((column - 1 >= 0) && tileColor == (_gamePanLst.get(column - 1).getComponent(row).getBackground())) {
column = column - 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
// Below
if ((row + 1 < 4) && tileColor == (_gamePanLst.get(column).getComponent(row + 1).getBackground())) {
row = row + 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
// Above
if ((row - 1 >= 0) && tileColor == (_gamePanLst.get(column).getComponent(row - 1).getBackground())) {
row = row - 1;
addTileToDelete(column, row);
deleteTileByColor(column, row, tileColor);
}
moveDownTiles();
}
public void moveDownTiles() {
for (int i = 0; i < _column; i++) {
for (int j = 0; j < _row; j++) {
if (_gamePanLst.get(i).getComponent(j).equals(_gameTileList.get(i).get(j))) {
_gamePanLst.get(i).remove(j);
_gamePanLst.get(i).add(getEmptyTile(), 0);
}
}
}
resetTileArrLst();
}
public void addTileToDelete(int column, int row) {
_gameTileList.get(column).set(row, (GameTile) _gamePanLst.get(column).getComponent(row));
System.out.println("지울 타일 추가 완료 : " + _gamePanLst.get(column).getComponent(row).getName());
}
public int get_exitCounter() {
return _exitCounter;
}
public void set_exitCounter(int _exitCounter) {
this._exitCounter = _exitCounter;
}
public GamePanel get_gamePanel() {
return _gamePanel;
}
public void set_gamePanel(GamePanel _gamePanel) {
this._gamePanel = _gamePanel;
}
public ArrayList<ArrayList<GameTile>> get_gameTilesList() {
return _gameTileList;
}
public void set_gameTilesList(ArrayList<ArrayList<GameTile>> _gameTilesList) {
this._gameTileList = _gameTilesList;
}
public ArrayList<Character> get_letterList() {
return _letterList;
}
public void set_letterList(ArrayList<Character> _letterList) {
this._letterList = _letterList;
}
public ArrayList<GamePanel> get_gamePanLst() {
return _gamePanLst;
}
public void set_gamePanLst(ArrayList<GamePanel> _gamePanLst) {
this._gamePanLst = _gamePanLst;
}
public void resetTileArrLst() {
if (_gameTileList.size() != 0) {
_gameTileList.clear();
}
for (int i = 0; i < _column; i++) {
_gameTileList.add(i, new ArrayList<GameTile>());
for (int j = 0; j < _row; j++) {
_gameTileList.get(i).add(getEmptyTile());
}
}
}
}

Java help! implementing a 2d array of a certain object, the object has multiple private data types and objects

I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.

Categories