static arraylist creating infinite instances of itself - java

My understanding is that a static variable will exist to be shared across all instances of the class that the variable resides in.
My code is as follows:
public class Game {
private static final ArrayList<Game> GAMESLIST = new ArrayList<Game>();
Random rand = new Random();
private int gameID;
private int teamScore1;
private int teamScore2;
private int temperature;
private String teamName1;
private String teamName2;
public void PlayGame(Team team1, Team team2, int value, String teamNameValue1, String teamNameValue2, Scheduler scheduler){
temperature = value;
int maxGoals = 2;
int iterator;
if(temperature > 12){
for(iterator = 0; iterator < temperature; ++iterator){
++maxGoals;
if(maxGoals == 8){
break;
}
}
}
teamScore1 = rand.nextInt(maxGoals);
teamScore2 = rand.nextInt(maxGoals);
teamName1 = teamNameValue1;
teamName2 = teamNameValue2;
++gameID;
System.out.println(teamScore1);
System.out.println(teamScore2);
GAMESLIST.add(this);
scheduler.PlayGame();
}
public void PrintStatistics(){
int iterator;
for(iterator = 0; iterator < this.GAMESLIST.size(); ++iterator){
System.out.println("Game# " +this.GAMESLIST.get(iterator).gameID);
System.out.println("Team 1: " +this.GAMESLIST.get(iterator).teamName1);
System.out.println("Team 2: " +this.GAMESLIST.get(iterator).teamName2);
System.out.println(GAMESLIST.get(iterator).teamScore1);
System.out.println(GAMESLIST.get(iterator).teamScore2);
System.out.println("Recorded temperature that day: " + GAMESLIST.get(iterator).temperature);
}
}
public class Scheduler {
Random rand = new Random();
private Team[] teams;
private Team team1, team2;
private Game game;
private int temperature;
private int numberOfColdDays = 0;
public Scheduler(){
}
public Scheduler(Game gameValue, Team[] teamsValue){
game = gameValue;
teams = teamsValue;
}
public void PlayGame(){
if(IsTooCold() == true){
System.out.println("Too cold to play!");
++numberOfColdDays;
if(numberOfColdDays < 3){
SoccerLeague.PlayGame(this);
}
else{
SoccerLeague.EndSeason(this);
}
}
else{
numberOfColdDays = 0;
TeamPicker(teams);
game.PlayGame(team1, team2, temperature, team1.teamName, team2.teamName, this);
}
}
public void TeamPicker(Team[] teams){
int value1;
int value2;
value1 = rand.nextInt(3);
team1 = teams[value1];
do{
value2 = rand.nextInt(3);
team2 = teams[value2];
}while(value1 == value2);
}
public boolean IsTooCold(){
boolean tOrF = false;
System.out.println("Is it too cold to play?");
this.temperature = rand.nextInt(30);
if(temperature < 7){
tOrF = true;
}
return tOrF;
}
public void PrintGames(){
}
}
When running the debugger in the IDE, I get an infinite amount of instances of this object created inside the ArrayList for one instance of type Game.
Also, after the specific conditions are met and it's time to print the ArrayList, the for loop will print at random a single iteration and print a random amount of the instances of that one iteration that was created earlier.
Is my code failing in Game class somewhere, in the PlayGame method or the PrintStatistics method?
Also, note that I have tried removing the this keyword entirely from the loop in the PrintStatistics method, but I still get the same result.
As always, any help is appreciated.
EDIT As requested, the scheduler class.
Regards, MYLESMAN

You have unobvious endless loop.
You have an method Game.PlayGame which adds your game to list and calls scheduler.PlayGame(). However scheduler.PlayGame() calls game.PlayGame() in its turns. It leads to adding game to gamelist many times and may lead to StackOverflowError and OutOfMemoryError.

Related

Any advice on how to fix this Stack Overflow error? Java

While developing a simple auto generating game of war in my free time, I ran into a "StackOverFlow" error.
Here is my Deck class where the error occurs:
It occurs in my compare() method. Any insight as to what I can do to avoid this error is accepted as I am struggling to understand what can be done to fix this and have little knowledge as to what this error even means besides my class doesn't have recursion done well. Thanks!
import java.util.*;
import java.math.*;
public class Deck
{
private int num = 0;
private int cardnum2 = 0;
private int cardnum = 0;
private int decrease = 0;
private int rnd = 0;
private int winner = 0;
private String suit = " ";
private int suitNum = 0;
private int val = 1;
private String name = "";
private ArrayList<Card> Deck = new ArrayList<Card>();
private Card[] cardCheck = new Card[51];
private ArrayList<Card> play1 = new ArrayList<Card>();
private ArrayList<Card> play2 = new ArrayList<Card>();
public Deck()
{
createDeck();
}
public void createDeck()
{
for(int i = 0; i < 4; i++)
{
val = 1;
suit = " ";
name = " ";
suitNum++;
System.out.println();
System.out.println();
for(int z = 0; z < 13; z++)
{
if(suitNum == 1)
{
suit = "Hearts";
}
if(suitNum == 2)
{
suit = "Diamonds";
}
if(suitNum == 3)
{
suit = "Spades";
}
if(suitNum == 4)
{
suit = "Clubs";
}
if(val == 1)
{
name = "Ace";
}
else if(val == 11)
{
name = "Jack";
}
else if(val == 12)
{
name = "Queen";
}
else if(val == 13)
{
name = "King";
}
else {
name = "";
}
Card myCards = new Card(val, suit, name);
Deck.add(myCards);
System.out.print(myCards + " ");
val++;
}
}
}
public void Deal()
{
int size = 52 / 2;
for(int i = 0; i < size; i++)
{
Random();
for(int z = 0; z < cardCheck.length; z++)
{
if(cardCheck[i] == null)
{
cardCheck[i] = Deck.get(rnd);
play1.add(cardCheck[i]);
System.out.println(play1);
}
else
{
Random();
}
}
}
System.out.println();
System.out.println();
for(int i = 0; i < size; i++){
Deck.remove(play1.get(i));
}
for(int i = 0; i < size; i++){
play2.add(Deck.get(i));
}
for(int i = 0; i < size; i++)
{
System.out.println(play2.get(i));
}
}
public void Random()
{
rnd = (int)(Math.random() * 52) - decrease;
}
public void flip()
{
if(play1.indexOf(cardnum) >= play1.size() || play2.indexOf(cardnum2) >= play2.size())
{
cardnum = (int)(Math.random() * play1.size());
System.out.println(play1.get(cardnum));
cardnum2 = (int)(Math.random() * play2.size());
System.out.println(play2.get(cardnum2));
}
}
public void compare()
{
System.out.println("War!!!\n");
if(play1.get(cardnum).getNum() > play2.get(cardnum2).getNum())
{
System.out.println();
winner = 1;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play1.add(play2.get(cardnum2));
play2.remove(cardnum2);
System.out.println("Player 1 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() < play2.get(cardnum2).getNum())
{
System.out.println();
winner = 2;
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
play2.add(play1.get(cardnum));
play1.remove(cardnum);
System.out.println("Player 2 took the cards!");
System.out.println();
printDecks();
}
if(play1.get(cardnum).getNum() == play2.get(cardnum2).getNum())
{
System.out.println();
System.out.println(play1.get(cardnum) + " vs " + play2.get(cardnum2));
System.out.println("War!!");
winner = 0;
flip();
flip();
flip();
compare();
System.out.println();
printDecks();
}
}
public void playW()
{
while(play1.size() > 0 || play2.size() > 0)
{
flip();
compare();
}
}
public void printDecks()
{
for(int i = 0; i < play1.size(); i++)
{
System.out.print(play1.get(i) + " ");
}
System.out.println();
for(int i = 0; i < play2.size(); i++)
{
System.out.print(play2.get(i) + " ");
}
System.out.println();
System.out.println("Player 1 has: " + play1.size() + " cards");
System.out.println("Player 2 has: " + play2.size() + " cards");
}
}
This is more a comment but it became too long.
There is a lot to say about this code. Use switch case instead of series of if. Or at least use if else. What is the point of a for loop if you use cases inside? What is the 'i' variable for if you then increment yourself a suitNum variable? Don't use capital letter for methods. Only classes. Why does Random edits a variable and returns void? It would be more logical that random() returns the result you want and this way you get free of the useless variable 'rnd'
There is a lot more to say but it is a good start. About your error, in short, a stack overflow means that your program is using too much memory. This is especially common in code that contains an infinite recursive loop. Here, the infinite recursion is due to the compare method called inside the compare method...
and have little knowledge as to what this error even means besides my class doesn't have recursion done well.
Yes, your code has recursion, and it's easy to find. You know that the problem is coming from within the compare method, and so all you have to do is look within that method for compare() and find out where you're having the method call itself.
The solution is not to call the method within itself, and why should it be doing this anyway?
You're having the issue partly because your class structure is broken. The Deck class is class that should represent the structure and behavior of a deck of cards, nothing more and nothing less, It should have methods like public void shuffle(), like public Card Deal(), and such. It should not have any code that directly interacts with the user, and this code should go elsewhere, perhaps in your driver or Game class, or even as separate class(es) entirely.
I'm guessing that you'll also want to have a Hand class, one that holds a player's hand, and perhaps inside of this class, have a compare method that compares the current Hand with another Hand, passed in as a parameter.
You'll also want a Game class should have a game-loop that controls play, that ends when there is a winner or a draw, that holds the Deck, that holds 1 or more Player objects...
e.g.,
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
public enum Value {
//....
}
public class Card {
private Suit suit;
private Value value;
// TODO: constructor, methods including equals, hashCode
}
public class Deck {
private List<Card> cards = new ArrayList<>();
public Card deal() {
return cards.remove(0);
}
public void shuffle() {
Collection.shuffle(cards);
}
//....
}
class Player {
// either use a List in each Player or create a class called hand
private List<Card> hand;
private int cash;
private String name;
private Game game;
// TODO: constructor
// TODO: methods including receiveCard(Card c), List<Card> showHand(),...
}
public class Game {
private Player p1;
private Player p2;
private Deck deck;
private int moneyPot;

Static Method Java confusion

Room Class:
public abstract class Room {
public abstract int cost();
public static Room mostExpensive = null;
public static int highestCost = 0;
public static Room mostExpensive() {
return mostExpensive;
}
}
Lab Class:
public class Lab extends Room{
public final int LAB_CHAIR_PRICE = 50;
int labChairs;
int computers;
private final int COMPUTER_COST = 1000;
public Lab(int labChairs, int computers) {
this.labChairs = labChairs;
this.computers = computers;
if (this.cost() > highestCost) {
mostExpensive = this;
highestCost = this.cost();
}
}
public int cost() {
return ((LAB_CHAIR_PRICE * labChairs) + (COMPUTER_COST * computers));
}
}
LectureHall Class:
public class LectureHall extends Room {
private final int LECTURE_CHAIR_PRICE = 100;
int lectureChairs;
boolean isData;
private final int DATA_PROJECTOR_COST = 5000;
int dataProjector;
public LectureHall(int lectureChairs, boolean isData) {
this.lectureChairs = lectureChairs;
if (this.isData = isData) {
this.dataProjector = 1;
if (this.cost() > highestCost) {
mostExpensive = this;
highestCost = this.cost();
}
}
}
public int cost(){
return ((LECTURE_CHAIR_PRICE * lectureChairs) + (DATA_PROJECTOR_COST * dataProjector));
}
}
Test Class
public class Test {
public static void main(String[] args) {
// An array of rooms for a proposed new building
Room rooms[] = new Room[4];
// small lecture hall with a data projector
rooms[0] = new LectureHall(40, true);
// large lecture hall seating 500, with no data projector
rooms[1] = new LectureHall(500, false);
// lab with seats for 50 and a computer for every two
rooms[2] = new Lab(50,25);
// smaller lab with seats for 10 and a computer for each
rooms[3] = new Lab(10,10);
int totalCost = 0;
for (int i = 0; i < rooms.length; i++) {
System.out.println("room " + i + " costs $" + rooms[i].cost());
totalCost += rooms[i].cost();
}
System.out.println("total cost: $" + totalCost);
Room r = Room.mostExpensive(); // the most expensive room created
// by the program
System.out.println("the most expensive room costs $" + r.cost());
}
}
So i'm having a little trouble with the mostExpensive method(). Its a static method and I declared it in the room class, but its used by the other methods. Its supposed to find the most expensive Room. However, it doesn't find the most expensive one, and it tells me that 27500 is the most expensive (which is not). Also I had a question about the Room class. In the constructor i set mostExpensive = this. Does that work? I'm a little confused as to how all of this works, and how I can do it correctly.
In this constructor, the "mostExpensive" is only modified if there is a projector.
public LectureHall(int lectureChairs, boolean isData){
this.lectureChairs = lectureChairs;
if (this.isData = isData){
this.dataProjector = 1;
if (this.cost() > highestCost){
mostExpensive = this;
highestCost = this.cost();
}
}
}
Fix:
public LectureHall(int lectureChairs, boolean isData){
this.lectureChairs = lectureChairs;
if (this.isData = isData){
this.dataProjector = 1;
}
if (this.cost() > highestCost){
mostExpensive = this;
highestCost = this.cost();
}
}
But one should not compute overall state in the constructor of a single object. This is poor design. Keep track of Rooms in some class - either Room or something new, e.g Building. Then compute the "most expensive" from whatever you have in Room. Imagine: what happens if a projector is removed? Or added in another existing Lecture Room? The possibilities of making errors are overwhelming.

Why am I getting a null pointer exception and should I use reflection?

I'm writing a program that should play the game HiLo. HiLo is a game, where a random number is generated and the player has to guess it. If they guess wrong, they are told if the answer is higher or lower than their guess, then they are allowed to guess again. My program should have the ability to limit the number of guesses if needed, set the range of values the answer can be chosen from (and therefore the range of guesses too). I also need to have the option of selecting whether a human will play the game, or if I will let the computer play, and if so, at what skill level (bad, medium, good).
I've written 3 classes: GameManager, HiLo and Player.
The GameManager class allows multiple games to be played and keeps track of the number of wins.
public class GameManager {
private HiLo game;
private int wins;
private int totalRounds;
private int player;
/**
* Constructor for objects of class GameManager
*/
public GameManager()
{
player = 2;
}
public void playGames(int rounds)
{
int i = 0;
while(i < rounds) {
game = new HiLo(player);
game.play();
wins += game.getHasWon();
i++;
}
totalRounds += rounds;
}
public void changePlayer(int playerType)
{
player = playerType;
}
} //This should be indented better, but it won't format properly, apologies
The HiLo class basically sets up and plays an individual game of HiLo.
public class HiLo {
private int guessLimit;
private int lowerLimit;
private int upperLimit;
private int guesses;
private int answer;
private boolean hasWon;
private Player player;
private String result;
/**
* Constructor for objects of class HiLo
*/
public HiLo(int playerType) //Set default values
{
guessLimit = 10;
lowerLimit = 0;
upperLimit = 50;
hasWon = false;
player = new Player(playerType);
}
public HiLo(int guessLimit, int lowerLimit, int upperLimit, int playerType) //Overload
{
this.guessLimit = guessLimit;
this.lowerLimit = lowerLimit;
this.upperLimit = upperLimit;
hasWon = false;
player = new Player(playerType);
}
//Returns lower limit
public int getLowerLimit()
{
return lowerLimit;
}
//Returns upper limit
public int getUpperLimit()
{
return upperLimit;
}
//Returns 1 if hasWon is true and 0 if hasWon is false
public int getHasWon()
{
if(hasWon) {
return 1;
} else {
return 0;
}
}
//Returns the number of guesses so far
public int getGuesses()
{
return guesses;
}
//Play a game of HiLo
public void play()
{
answer = randInt(lowerLimit, upperLimit);
guesses = 0;
while(guesses < guessLimit) {
int guess = player.guess(); //This gets a guess from the player
result = isCorrect(guess); //Was the guess correct?
if(result.equals("Win")) {
break; //If the player has won, break from the while loop
}
guesses++;
}
}
//Checks if the guess was correct
public String isCorrect(int guess)
{
if(guess == answer) {
hasWon = true;
return "Win";
} else if(guess < answer) {
lowerLimit = guess;
return "Higher";
} else {
upperLimit = guess;
return "Lower";
}
}
public int randInt(int min, int max)
{
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
}
The Player Class determines which player is playing (0 = human, 1 = badComp, 2 = medComp, 3 = goodComp) and the strategy they are going to use to guess.
import java.util.Random;
import java.util.Scanner;
public class Player {
private int playerType;
private HiLo game;
private int range;
private int lowestLimit; //This is the starting value of lowerLimit
/**
* Constructor for objects of class Player
*/
public Player(int playerType)
{
if(playerType < 0 || playerType > 3) {
System.out.println("ERROR. Please pick a valid playerType");
}
this.playerType = playerType;
range = 0;
range = setRange();
lowestLimit = game.getLowerLimit();
}
public int guess()
{
if(playerType == 0) {
return humanPlayer();
} else if(playerType == 1) {
return badComputerPlayer();
} else if(playerType == 2) {
return mediumComputerPlayer();
} else {
return goodComputerPlayer();
}
}
//Guess from a good computer player
public int goodComputerPlayer()
{
return (game.getUpperLimit() - game.getLowerLimit())/2;
}
//Guess from a medium computer player
public int mediumComputerPlayer()
{
return randInt(game.getLowerLimit(), game.getUpperLimit());
}
//Guess from a bad computer player
public int badComputerPlayer()
{
return randInt(lowestLimit, range);
}
public int humanPlayer()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("enter an integer");
int myint = keyboard.nextInt();
return myint;
}
//Generates a random number in the range maz-min
public int randInt(int min, int max)
{
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
//Set the range of values to guess from for bad player
public int setRange()
{
int r = game.getUpperLimit() - game.getLowerLimit();
return r;
}
}
When I create an object from the HiLo class and input all the arguments, I get a NullPointException:
java.lang.NullPointerException
at Player.setRange(Player.java:75)
at Player.<init>(Player.java:26)
at HiLo.<init>(HiLo.java:35)
I'm new to both programming and Java, and this is my first NullPointException error. I've read some of the other posts on them, but I can't figure it out.
I also don't think the player class is doing exactly what I want it too. Each new instance of the Player class is conceptually tied to the instance of the HiLo game that creates that instance, because a HiLo game can only have one player at a time. I want the new instance of the Player class to reference the instance of the HiLo class that created it:
lowestLimit = game.getLowerLimit();
I'm trying to set lowestLimit = to the lower limit of the instance of the HiLo game that created this Player instance, however I think that's I'm just referencing the object game created from the HiLo class, rather than the instance that created this Player instance. Sorry if this is confusing, I'm trying my best to explain :)
I do this in quite a few other methods inside the Player class too. I've read something about using reflection to potentially solve this, but I'm really not sure I understand it yet.
Any help and/or thoughts would be greatly appreciated,
Thanks.
EDIT: Just thought I'd let you know that I'm using the BlueJ environment.
The setRange() method depends on game not being null. Because setRange() is called in the Player's constructor, it will always throw a NullPointerException because the game instance variable has not been initialized.
One way to fix this is to make Player's constructor accept a HiLo parameter, and set game to that value before calling setRange():
public Player(int playerType, HiLo game) {
this.game = game;
// ...
}
Now you need to update the player = new Player(playerType); statement to use the correct parameters. Because that statement is in an instance method of HiLo, we can simply pass this as the second parameter:
player = new Player(playerType, this);
Here is the setRange code:
public int setRange() {
int r = game.getUpperLimit() - game.getLowerLimit();
return r;
}
There is only one possible explanation for that method throwing an NPE. That is - game is null.
Work with that ... figure out why game is null ... and fix it.
Hint: there are two distinct game fields in your code. You are initializing one of them ... but not the other one.
... and should I use reflection?
Reflection is not a solution to NPE's.

How to sort an array when it is filled with numbers from a get method

Arrays.sort() gives and error of:
FiveDice.java:19: error: no suitable method found for sort(int)
Arrays.sort(compNums);
If I take anything out of the for loop, it thinks thee is only 1 number or gives an error. What other sorting options would be usable?
import java.util.*;
public class FiveDice {
public static void main(String[] args) {
int x;
int compNums = 0;
int playerNums;
Die[] comp = new Die[5];
Die[] player = new Die[5];
System.out.print("The highest combination wins! \n5 of a kind, 4 of a kind, 3 of a kind, or a pair\n");
//computer
System.out.print("Computer rolled: ");
for(x = 0; x < comp.length; ++x) {
comp[x] = new Die();
compNums = comp[x].getRoll();
//Arrays.sort(compNums); <--does not work
System.out.print(compNums + " ");
}
//player
System.out.print("\nYou rolled: \t ");
for(x = 0; x < player.length; ++x) {
player[x] = new Die();
playerNums = player[x].getRoll();
System.out.print(playerNums + " ");
}
}
}
die class
public class Die {
int roll;
final int HIGHEST_DIE_VALUE = 6;
final int LOWEST_DIE_VALUE = 1;
public Die()
{ }
public int getRoll() {
roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
return roll; }
public void setRoll()
{ this.roll = roll; }
}
Easiest way is to implement Comparable to Die class , set value of roll in constructor of Die not in the getter method and your problem is solved.
public class Die implements Comparable<Die> {
private int roll;
final int HIGHEST_DIE_VALUE = 6;
final int LOWEST_DIE_VALUE = 1;
public Die() {
roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
}
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public int compareTo(Die d) {
return new Integer(d.getRoll()).compareTo(new Integer(this.getRoll()));
}
}
now Arrays.sort(Die[]) will sort the array of Die.
You don't have to use 2 arrays for the sorting. If you implement the Comparable<T> interface, your classes can be sorted by Java Collections API. In your case, Die class can implement Comparable<T> and provide a way for the Java framework to compare dice values.
Take a look at the Java API:
http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
In your case:
public class Die implements Comparable<Die>{
int roll;
final int HIGHEST_DIE_VALUE = 6;
final int LOWEST_DIE_VALUE = 1;
public Die() { }
public int computeRoll() {
roll = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
return roll;
}
// I also changed this to store the value
public int getRoll() {
return roll;
}
public void setRoll() { this.roll = roll; }
// This is the method you have to implement
public int compareTo(Die d) {
if(getRoll() < d.getRoll()) return -1;
if(getRoll() > d.getRoll()) return +1;
if(getRoll() == d.getRoll()) return 0;
}
}
Whenever you have a Collection of Dies, like an ArrayList or LinkedList, you simply sort the collection itself. Below is a sample code.
ArrayList<Die> myCollection = new ArrayList<Die>();
myCollection.add(die1);
// more array population code
// ...
Collections.sort(myCollection);
You can't perform sort() on compNums because it is a single value. You declare it as an int value, rather than as an array of integers.
Instead, you should make compNums an array, populate it with the Die roll values, and then perform a sort operation on the resultant array. I believe the following will achieve what you are after.
int[] compNums = new int[5];
...
for(x = 0; x < comp.length; ++x) {
comp[x] = new Die();
compNums[x] = comp[x].getRoll();
}
Arrays.sort(compNums);
// print results
you must pass an array to the Array.Sort(arr) not parameter you must do something like this Array.Sort(int[]compNums);
and if you are using a anonymous type like comp[]compNums you must do it like this
java.util.Arrays.sort(comp[]compNums, new java.util.Comparator<Object[]>() {
public int compare(Object a[], Object b[]) {
if(something)
return 1;
return 0;
}
});

implementing a method from one class to another?

I am making a program for airplane seating arrangements for a class and i ended up making two toString methods but when I run the program the toString method in my airplane class is making something not work specifically:
str= str + seats[i][j].toString();
I believe that simply deleting the toString method in the seat class and somehow putting it back into the airplane class toString method would fix the problem or make it simpler. What's wrong?
Airplane class:
public class Airplane
{
private Seat [ ] [ ] seats;
public static final int FIRST_CLASS = 1;
public static final int ECONOMY = 2;
private static final int FC_ROWS = 5;
private static final int FC_COLS = 4;
private static final int ECONOMY_ROWS = 5;
private static final int ECONOMY_COLS = 6;
public Airplane()
{
seats = new Seat[FC_ROWS][ECONOMY_COLS];
}
public String toString()
{
String str = "";
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
str= str + seats[i][j].toString();
}
str = str + "\n";
}
return str;
}
}
Seat Class:
public class Seat
{
private int seatType;
private boolean isReserved;
public static final int WINDOW = 1;
public static final int AISLE = 2;
public static final int CENTER = 3;
public Seat(int inSeatType)
{
seatType = inSeatType;
isReserved = false;
}
public int getSeatType()
{
return seatType;
}
public void reserveSeat()
{
isReserved = true;
}
public boolean isAvailable()
{
if (!isReserved)
{
return true;
}
else return false;
}
public String toString()
{
if(isReserved == false)
{
return "*";
}
else return "";
}
}
In Seat.toString you should print a " " not "".
You're array is FC_ROWS by ECONOMY_COLS, so you're not creating all the seats. You should probably have two arrays (one for FC, one for Economy), since FC_ROWS != ECONOMY_ROWS.
You aren't actually creating Seats in your constructor. Use a nested loop to create them, otherwise you will get a NullPointerException. Creating an array doesn't create the objects contained in the array.
When you're creating the seats in the Airplane constructor, use if statements to figure out if the seat is supposed to be a Window, Aisle, etc.
seats seems to does not have Seat's instance.
Add this code :
for (int i=0; i<FC_ROWS; i++) {
for (int j=0; j<ECONOMY_COLS; j++)
{
seats[i][j] = new Seat();
}
}
below this :
seats = new Seat[FC_ROWS][ECONOMY_COLS];
I think that in Seat::toString, you mean to return " " (a space) if it isn't reserved.

Categories