ArrayIndexOutOfBoundsException when repeatedly removing and creating objects [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am building the object with the classical Nim game, and there are some methods dealing with the player data. I bumped into this problem when testing my code, and couldn't figure it out.
This problem appeared when I add a player in an array, removing it after. Then, adding a player again. It showed: Index 1 out of bounds for length 1. What I've tried is to filter the null position when I remove the player data.
Any help is highly appreciated. And thank you all for the patience and time solving it!
The code is a little bit longer, but related.
Here is the related code from class Nimsys, main method.
public static void addPlayer(String [] name) {
if (name != null && name.length == 3) {
for (int i = 0; i < NimPlayer.getCounter(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exists.\n");// Test if player has been created
return;
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
return;
}
System.out.println("Not Valid! Please enter again!");
}
public static void searchAndRemovePlayer(String user) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
String userName =playerList[i].getUserName().trim();
if (userName.equals(user)) {
playerList[i] = null;
System.out.println("Remove successfully!");
NimPlayer.setPlayerList(playerList);
return;
}
}
System.out.println("The player does not exist.\n");
}
public static void main(String[] args) {
System.out.println("Welcome to Nim\n");
//Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inputName = in.nextLine();
String[] name = splitName(inputName);
addPlayer(name);
}
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
Here is part of my NimPlayer class:
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
private int score;
private int gamePlayed;
private static int counter;
private static final int SIZE = 10;
private static NimPlayer[] playerList = new NimPlayer[SIZE]; // set an array here
//define NimPlayer data type
public NimPlayer(String userName, String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (counter < SIZE) {
playerList[counter++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getCounter() {
return counter;
}
public static NimPlayer [] getPlayer() {
NimPlayer[] nimPlayers = Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
counter = nimPlayers.length; //update the counter
return nimPlayers;
}
public static void setPlayerList(NimPlayer [] newplayerList) {
NimPlayer.playerList = newplayerList;

1. Replace
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.equals("")) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.next();
if (commandin.equals("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
playerList[i] = null;
NimPlayer.setPlayerList(playerList);
}
System.out.println("Remove all the players\n");
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
if (!user.equals("")) {
searchAndRemovePlayer(user);
Arrays.stream(NimPlayer.getPlayer()).filter(Objects::nonNull).toArray();
}
}
with
if (commandin.equals("removeplayer")) {
String user = in.nextLine().trim();
if (user.isEmpty()) {
System.out.println("Are you sure you want to remove all players? (y/n)");
commandin = in.nextLine();
if (commandin.equalsIgnoreCase("y")) {
NimPlayer [] playerList = NimPlayer.getPlayer();
for (int i = 0; i < playerList.length; i++) {
NimPlayer.removePlayer(playerList[i]);
}
System.out.println("Removed all the players\n");
}
} else {
searchAndRemovePlayer(user);
}
}
2. Change the following methods as given below:
public static void searchAndRemovePlayer(String user) {
NimPlayer[] playerList = NimPlayer.getPlayerList();
for (int i = 0; i < playerList.length; i++) {
String userName = playerList[i].getUserName().trim();
if (userName.equals(user)) {
NimPlayer.removePlayer(playerList[i]);
System.out.println("The player, " + user + " removed successfully!");
return;
}
}
System.out.println("The player, " + user + " does not exist.\n");
}
public static NimPlayer [] getPlayer() {
return Arrays.stream(playerList).filter(Objects::nonNull).toArray(NimPlayer[]::new);
}
2. Instead of exposing the playerList to be set from outside, you should remove its public setter and create public static void removePlayer similar to public static void createPlayer as follows:
public static void removePlayer(NimPlayer player) {
int i;
for (i = 0; i < playerList.length; i++) {
if (playerList[i] != null && playerList[i].getUserName().equals(player.getUserName())) {
break;
}
}
for (int j = i; j < playerList.length - 1; j++) {
playerList[j] = playerList[j + 1];
}
counter--;
}
Important note: Never put setting operation within getter, the way you have done in your method, getPlayer().

You need to use Iterator and call remove() on iterator instead of assigning to null.
Duplicate from: Removing items from a list

You shouldn't do a "playerList[i] = null;" for removing a player. Use an ArrayList instead and use the ArrayList's .remove method to remove a player. don't keep track of counter variables.

Related

ArrayList-"for-loop" exits code at .size() call, what's wrong?

As part of the login method for my fictive bank, i have a Luhn algorithm set up to validate the users ID.
It seems to check through and comes back valid, but when i list the ArrayList (with the for-loop) to see if there's a corresponding match or not, the code seems to breaks out when it hits kList.size()
See this :
public void logIn() {
System.out.print("Please enter your ID (10 numbers):");
String x = s.nextLine();
if (luhnCheck(x)) {
for (i = 0; i < k.kList.size(); i++) { //<-----ISSUE!
if (k.kList.get(i).getPnr().equals(x)) {
tempKund = k.kList.get(i);
}
}
} else {
System.out.println("You are not a customer, please register!");
System.out.print("Enter name:");
String n = s.nextLine();
k.createKund(x, n); //sends values to create customer method
kundMeny1(); // customer menu...
}
}
public boolean luhnCheck(String v) {
int sum = 0;
boolean alternate = false;
for (int i = v.length() - 1; i >= 0; i--) {
int n = Integer.parseInt(v.substring(i, i + 1));
if (alternate) {
n *= 2;
if (n > 9) {
n = (n % 10) + 1;
}
}
sum += n;
alternate = !alternate;
}
return (sum % 10 == 0);
}
Update: So apparently the problem doesn't seem to in the loop, but when the .size() tries to get the needed information. I'll paste some more of my code:
public class Bank {
Scanner s = new Scanner(System.in);
Kund k = new Kund(); //Used for communicating with the Kund(customer class)
Konto t = new Konto(); //Used for communicating with the Konto(account class)
Kund tempKund; //Temporary customer used to keep track of who's logged in
int i;
public static void main(String[] args) {
Bank b = new Bank();
b.mainMenu();
}
public void mainMenu() {
k.createKund("8908041207", "Adam Sears"); //Creates a customer
t.createKonto("1234567891", "3000"); //Creates a bank account
int user_choice = 3;
do { // Goes on to a Switch Case menu for the user...
Kund(Customer class)
public class Kund {
ArrayList<Kund> kList = new ArrayList<Kund>();
Kund knd;
String pnr; //Customer ID, used in validation
String name; //Customer name
public void kund() {
}
public String getPnr() {
return pnr;
}
public void setPnr(String x) {
this.pnr = x;
}
public String getName() {
return name;
}
public void setName(String z) {
this.name = z;
}
public void createKund(String p, String n) { //Creates the new customer
knd = new Kund();
knd.setPnr(p);
knd.setName(n);
addKund(knd);
}
public ArrayList<Kund> addKund(Kund s) { //Adds said customer to ArrayList
kList.add(s);
return kList;
}
This part of your code :
if (luhnCheck(x)) {
if (true) {
// Code
} else if (false) {
// Code
}
}
Should be replaced by this :
if (luhnCheck(x)) {
// Code
} else {
// Code
}
For the rest of the problem. I should know where you instantiate your k object.
We need more inforation on how k is instantiate, try to organize you snippet code, and try to debug at the
for (i = 0; i < k.kList.size(); i++) { //<-----ISSUE!
to see what kist contains?

Java - Creating Object Arrays [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I can't seem to work out these object arrays, I'm attempting to create a list of player names with values stored, each with an integer and some multiple strings for each.
This is what i'm working on so far, were object arrays the correct storage package for this? The error was in line 237 when I try to add a player in the class addPlayer: player[userCount].setName(name);
The error is:- Exception in thread "main" index out of bounds.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class PlayerKarma {
static Scanner input = new Scanner(System.in);
static private String[] username = {"name1","name2","test","moretesting","fervor","stackoverflow","imported","quaternion","jetstream"};
static private int[] karma = {1000,800,800,5,15,-4,-403,54,11,210};
static private boolean exit = false;
static private int maxKarmaChange = 10; //How much a players karma can change per day.
static Player[] userArray = new Player[10000];
//ArrayList<Player> userArray = new ArrayList<Player>();
static private int userCount = 0;
public static void main(String[] args)
{
while (!exit)
{
System.out.println("");
System.out.println("Select an option");
System.out.println("1: Display a player's karma");
System.out.println("3: Display all player names and karma");
System.out.println("5: Add player");
String command = input.nextLine();
switch(command)
{
//Display player's karma.
case "1": {
System.out.println("Enter a player's name: ");
String inputString = input.nextLine();
int playerindex = findPlayer(inputString);
if (playerindex == -1)
{
System.out.println("Player doesn't exist");
}
else //If the player exists.
{
System.out.println(userArray[playerindex].getName() + " has a karma of " + karma[userArray[playerindex].getKarma()]);
break;
}
break;}
//Display all player names and karma.
case "3": {getAllPlayerKarma(); sleep(1500); break;}
//Add player.
case "5": {
System.out.println("Enter a player's name:");
String inputString = input.nextLine();
if (userCount > 0) //If there is at least one user in the database.
{
int playerindex = findPlayer(inputString);
if (playerindex == -1)
{
addPlayer(inputString,0);
}
else //If the player exists.
{
break;
}
}
else //If there's no users.
{
addPlayer(inputString,0);
}
break;}
}
}
}
//Class creation for players.
public class Player
{
public String name;
public int karma;
//public String[] notes = new String[5];
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getKarma() {
return karma;
}
public void setKarma(int karma) {
this.karma = karma;
}
}
private static void getAllPlayerKarma() {
System.out.println("");
for (int k = 0; k < userCount; k++)
{
System.out.println(userArray[k].getName() + " has a karma of " + userArray[k].getKarma());
}
}
private static void setAllPlayerKarma(String karmaValue) {
System.out.println("");
for (int k = 0; k < username.length; k++)
{
int parseKarma = Integer.parseInt(karmaValue);
karma[k] = parseKarma;
}
System.out.println("All karma has been set to " + karmaValue);
}
private static void addPlayer(String name, int karma) {
//Adds a new user
Player[] player = new Player[userCount];
//Player[userCount] = new Player(userCount);
player[userCount].setName(name);
player[userCount].setKarma(karma);
//userArray[userCount].setName(name);
//userArray[userCount].setKarma(karma);
userCount++;
}
//Returns the index of the player in the database.
private static int findPlayer(String playerName) {
int playerIndex = -1;
for (int j = 0; j < userCount; j++)
{
System.out.println("Testing name: " + playerName + " against " + userArray[j].getName());
if (playerName.equals(userArray[j].getName())) {
playerIndex = j;
System.out.println("Match");
break;
}
else
{
//System.out.println("No match");
}
}
return playerIndex;
}
private static void sleep(int sleep) {
try {Thread.sleep(sleep);}
catch(InterruptedException ex) {
Thread.currentThread().interrupt();}
}
}
There are three problems with this code:
Player[] player = new Player[userCount];
player[userCount].setName(name);
Firstly, you're creating a new array each time - I suspect you want to populate userArray instead.
Secondly, you're creating an array of size userCount and then trying to use the element with index userCount - that's never going to work. Array indexes are 0-based, so an element with length 3 has valid indexes 0, 1 and 2 for example.
Thirdly, you're not creating a new Player object - so every element in the array is null. Even if you fixed the index, player[x].setKarma(karma) would throw a NullPointerException.
I suspect you want the method to look like this:
private static void addPlayer(String name, int karma) {
Player player = new Player();
player.setKarma(karma);
player.setName(name);
userArray[userCount] = player;
userCount++;
}
That's now fine, until the user count exceeds the length of your array. At that point, you should start looking at List<E> (and ArrayList<E> in particular).
You initialize usercount with the value of 0 and therefore create an array with the size of 0 Player[] player = new Player[userCount];, this leads to your error.

How can I make array of bowlers?

Following is the question which I am trying to solve-
In a one day international, the bowling figures of all the bowlers have been provided. The objective is to create an array of Bowler and return it. Note that the objects should appear in the same order in the array as they appear in the input.
The input is provided a string. The string has space demarcated details of each bowler provided as Name-Overs-Maiden-Runs-Wickets, like , “Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1″.Define a function that takes and prints the array of Bowler returned.
There is some error in the code but I am unable to detect it.
public class MakeArrayOfBowlers{
String name;
double over;
int maiden;
int runs;
int wickets;
public MakeArrayOfBowlers(String input){
String[] str=input.split("-");
this.name=str[0];
this.over=Double.parseDouble(str[1]);
this.maiden=Integer.parseInt(str[2]);
this.runs=Integer.parseInt(str[3]);
this.wickets=Integer.parseInt(str[4]);
}
public MakeArrayOfBowlers[] makeBowlers (String input){
MakeArrayOfBowlers str= (MakeArrayOfBowlers) new MakeArrayOfBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");
String[] str1 = input.split(" ");
MakeArrayOfBowlers bowler[]= new MakeArrayOfBowlers[str1.length];
for(int i = 0; i < str1.length; i++){
bowler = new MakeArrayOfBowlers[str1.length];
MakeArrayOfBowlers obj = new MakeArrayOfBowlers(str1[i]);
bowler[i] = obj;
}
return bowler;
}
}
You should make a own class bowler (constructor should be better but its your example ;)):
public class Bowler {
private String name;
private double over;
private int maiden;
private int runs;
private int wickets;
public Bowler(String input){
String[] str=input.split("-");
this.name=str[0];
this.over=Double.parseDouble(str[1]);
this.maiden=Integer.parseInt(str[2]);
this.runs=Integer.parseInt(str[3]);
this.wickets=Integer.parseInt(str[4]);
}
public String getName() {
return name;
}
public double getOver() {
return over;
}
public int getMaiden() {
return maiden;
}
public int getRuns() {
return runs;
}
public int getWickets() {
return wickets;
}
}
Than split your string and add it for every bowler:
public class MakeArrayOfBowlers {
public static Bowler[] makeBowlers(String input) {
String[] splitArray = input.split(" ");
Bowler[] bowler = new Bowler[splitArray.length];
for (int i = 0; i < splitArray.length; i++) {
bowler[i] = new Bowler(splitArray[i]);
}
return bowler;
}
public static void main(String[] args) {
Bowler[] bowlers = makeBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");
for (Bowler bowler : bowlers) {
System.out.println(bowler.getName()+"-"+bowler.getOver()+"-"+bowler.getMaiden()+"-"+bowler.getRuns()+"-"+bowler.getWickets());
}
}
}
You're re-initializing the bowler array inside the for-loop. Try removing that line (the first line inside your loop).
public MakeArrayOfBowlers[] makeBowlers (String input){
String[] str1 = input.split(" ");
MakeArrayOfBowlers bowlers[]= new MakeArrayOfBowlers[str1.length];
for(int i = 0; i < str1.length; i++){
MakeArrayOfBowler bowler = new MakeArrayOfBowlers(str1[i]);
bowlers[i] = obj;
}
return bowlers;
}
From your main function call
MakeArrayOfBowlers o = new MakeArrayOfBowlers();
MakeArrayOfBowlers[] b = o.makeBowlers("Zaheer-10-1-55-0 Harbhajan-8.4-0-44-2 Ishant-10-0-71-1");

Writing on an output file

I am stuck on this part where it does not write to an output file
the first class is contact I had to modify this is not my class is the authors class
I just had to use it
//********************************************************************
// Contact.java Author: Lewis/Loftus
//
// Represents a phone contact.
//********************************************************************
public class Contact implements Comparable
{
private String firstName, lastName, phone;
//-----------------------------------------------------------------
// Constructor: Sets up this contact with the specified data.
//-----------------------------------------------------------------
public Contact (String first, String last, String telephone)
{
firstName = first;
lastName = last;
phone = telephone;
}
//-----------------------------------------------------------------
// Returns a description of this contact as a string.
//-----------------------------------------------------------------
public String toString ()
{
return lastName + ", " + firstName + "\t" + phone;
}
//-----------------------------------------------------------------
// Returns true if the first and last names of this contact match
// those of the parameter.
//-----------------------------------------------------------------
public boolean equals (Object other)
{
return (lastName.equals(((Contact)other).getLastName()) &&
firstName.equals(((Contact)other).getFirstName()));
}
//-----------------------------------------------------------------
// Uses both last and first names to determine ordering.
//-----------------------------------------------------------------
public int compareTo (Object other)
{
int result;
String otherFirst = ((Contact)other).getFirstName();
String otherLast = ((Contact)other).getLastName();
if (lastName.equals(otherLast))
result = firstName.compareTo(otherFirst);
else
result = lastName.compareTo(otherLast);
return result;
}
//-----------------------------------------------------------------
// First name accessor.
//-----------------------------------------------------------------
public String getFirstName ()
{
return firstName;
}
//-----------------------------------------------------------------
// Last name accessor.
//-----------------------------------------------------------------
public String getLastName ()
{
return lastName;
}
}
this class oes the sorting this is fine. it does the sorting no prblem
public class Sorting {
public static void bubbleSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[i + 1]) > 0)
{ //swap check
Comparable tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = tmp;
}
}
bubbleSortRecursive(data, lastIndex);
}
}
public static void selectionSortRecursive(Comparable[] data, int n)
{
if (n < 2)
{
return;
}
else
{
int lastIndex = n - 1;
int largestIndex = lastIndex;
for (int i = 0; i < lastIndex; i++)
{
if (data[i].compareTo(data[largestIndex]) > 0)
{
largestIndex = i;
}
}
if (largestIndex != lastIndex)
{ //swap check
Comparable tmp = data[lastIndex];
data[lastIndex] = data[largestIndex];
data[largestIndex] = tmp;
}
selectionSortRecursive(data, n - 1);
}
}
}
this is the part I need help with. It is not outputing to he p4output.txt, i dont know what the problem is.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestProject4 {
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
}
private static void doBubbleSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.bubbleSortRecursive(contacts, contacts.length);
System.out.println("\nAfter bubbleSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void doSelectionSortRecursive()
{
Contact[] contacts = createContacts();
System.out.println("Before selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
Sorting.selectionSortRecursive(contacts, contacts.length);
System.out.println("\nAfter selectionSortRecursive(): ");
for (int i=0; i<contacts.length; i++)
System.out.println(contacts[i].toString());
}
private static void printContacts(Contact[] contacts)
{
try
{
// this part I need help with it is not outputing in the text file
File file = new File("p4output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
for (Contact contact : contacts)
{
bw.write(contact.toString());
}
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println("\t" + contacts);
}
public static Contact[] createContacts()
{
return new Contact[]
{
new Contact("John" , "Smith" , "610-555-7384"),
new Contact("Sarah" , "Barnes" , "215-555-3827"),
new Contact("Mark" , "Riley", "333-333-3333"),
new Contact("Laura" , "Getz" ,"663-555-3984"),
new Contact("Larry" , "Smith" , "464-555-3489"),
new Contact("Frank" , "Phelps" , "322-555-2284"),
new Contact("Mario" , "Guzman" , "804-555-9066"),
new Contact("Marsha" , "Grant" , "243-555-2837"),
};
}
}
According to Eclipse, you never call/use printContacts(Contact[] contacts); method
Your printContacts(Contact[] contacts); contains the statements to write a file.
You don't appear to call the function printContacts() in your program. Try calling it after you do your contact creation and sorting.
It might look like this:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
doSelectionSortRecursive();
printContacts(contactArray);//inserted code
}
Also, when you call your sorting methods, doSelectionSortRecursive(), you don't return the list of contacts. Make a return statement for it and then put the contact array into your printContacts function.
Here's an example:
public static void main(String[] args)
{
doBubbleSortRecursive();
System.out.println();
System.out.println();
Contact[] contacts = doSelectionSortRecursive();
printContacts(contacts);
}
public static Contact[] doSelectionSortRecursive(){
Contact[] contacts = createContacts();
//your sorting code
return contacts;
}
Using this method allows you to get the array of contacts from the method once it has been sorted.

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