I have an object class
public class Film implements Comparable<Film>
I'm using Eclipse and would like to know why Film is underlined in red with the error saying:
The type Film must implement the inherited abstract method Comparable<Film>.compareTo<Film>
And now to my main question:
How would I get the max/min user submitted film length and title?
My object class Film has getter and setter methods for the Title of the film and the Length of the film and a toString method. Following this article (#3) I created two more methods in my object class:
public int max(Film maxLength){
int compareLength = ((Film) maxLength).getLength();
return this.length - compareLength;
}
public int min(Film minLength){
int compareLength = ((Film) minLength).getLength();
return compareLength - this.length;
}
Could I use these to find and print max/min values of the user submitted film lengths?
If so, how?
If not, what is the proper way of doing this?
The test class is as follows:
import java.util.Scanner;
public class test {
public static void main (String[] args){
Film[] f = new Film[3];
Scanner input = new Scanner(System.in);
for (int i=0;i<3;i++){
f[i] = new Film();
System.out.println("Enter Film Length:");
f[i].setLength(input.nextInt());
input.nextLine();
System.out.println("Enter Title:");
f[i].setTitle(input.nextLine());
}
input.close();
for (int i = 0; i < 3; i++) {
System.out.println(f[i].toString());
}
}
}
The Film class implements Comparable<Film>. What this means is that you must implement a method called compareTo() in class Film that will provide an ordering for objects of this class.
#Override
public int compareTo(Film that) {
// Order by film length
return Integer.compare(this.length, that.length);
}
If you only need to sort the objects by film length you can just use Arrays.sort():
Film[] films = new Film[3];
// put the objects into the array
Arrays.sort(films);
Then films[0] will contain the film with the shortest length, while the last element will be the film with the longest length.
If you need to compare by other fields, such as film title, you can create a custom comparator:
class FilmTitleComparator implements Comparator<Film> {
public int compare(Film a, Film b) {
return Integer.compare(a.getTitle().length(), b.getTitle().length());
}
}
And pass it to Arrays.sort()
FilmTitleComparator titleComparator = new FilmTitleComparator();
Arrays.sort(films, titleComparator);
Then films[0] will contain the film with the shortest title, while the last element will be the film with the longest title.
For simplicity, I stubbed your Film class to show a trivial example of how to implement Comparable
public class Film implements Comparable<Film> {
int maxLength;
int minLength;
String title;
public Film() {
this.maxLength = 0;
this.minLength = 0;
this.title = "";
}
// implement this method to accomplish comparison
public int compareTo(Film f) {
int result = 0; // the result to compute.
if ( this.equals(f) ) {
result = 0; // these objects are actually equal
}
// compare using meaningful data
else if ( f != null) {
// check to see if this film is greater than the specified film
if ( this.getMaxLength() > f.getMaxLength() ) {
// this film is comparatively greater, return > 0
result = 1;
}
else if ( this.getMaxLength() == f.getMaxLength() ) {
// these two films are comparatively equal
result = 0;
}
else {
// this film is comparatively less than the specified film
result = -1;
}
// similarly, you could also check min, but there's really no reason to do that unless your implementation calls for it.
}
else {
throw new IllegalArgumentException("null Film object not allowed here...");
}
return result;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Film film = (Film) o;
if (maxLength != film.maxLength) return false;
if (minLength != film.minLength) return false;
if (!title.equals(film.title)) return false;
return true;
}
#Override
public int hashCode() {
int result = maxLength;
result = 31 * result + minLength;
result = 31 * result + title.hashCode();
return result;
}
public int getMaxLength() {
return maxLength;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public int getMinLength() {
return minLength;
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
}
To fix your test to actually use such an implementation (it doesn't really test anything...), you could do:
import java.util.Scanner;
public class test {
public static void main (String[] args){
Film lastFilm = null; // arbitrary reference to film
Film[] f = new Film[3];
Scanner input = new Scanner(System.in);
for (int i=0;i<3;i++){
f[i] = new Film();
System.out.println("Enter Film Length:");
f[i].setLength(input.nextInt());
input.nextLine();
System.out.println("Enter Title:");
f[i].setTitle(input.nextLine());
}
input.close();
for (int i = 0; i < 3; i++) {
if ( lastFilm != null ) {
// compare the films to test. current to last film
if ( f[i].compareTo(lastFilm) > 0 ) {
System.out.println(f[i].getTitle() + " is greater than " + lastFilm.getTitle()");
}
else if ( f[i].compareTo(lastFilm) < 0 ) {
System.out.println(f[i].getTitle() + " is less than " + lastFilm.getTitle()");
}
else {
System.out.println(f[i].getTitle() + " is equal to " + lastFilm.getTitle()");
}
}
System.out.println(f[i].toString());
lastFilm = f[i];
}
}
}
Something like this can get you started... good luck
Another solution would be to implement Comparable<Film>:
#Override
public int compareTo(Film that) {
return this.length - that.length;
}
And use org.apache.commons.lang3.ObjectUtils#min or org.apache.commons.lang3.ObjectUtils#max like:
Film min = ObjectUtils.min(film1, film2);
Film max = ObjectUtils.max(film1, film2);
Related
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?
Okay I cannot for the life of me figure out how to sort my data by tournament placings. Here is my code.
if (o == 5) {
double RD, t, old, x;
String tournament, player;
int a, number_of_players, place;
place = 0;
ArrayList<player> players = new ArrayList<player> ();
ArrayList<placeDisplay> placeVar = new ArrayList<placeDisplay> ();
List<placeDisplay> sort = new ArrayList<placeDisplay> ();
System.out.println("1:Add a tournament \t2:View Existing");
a = keyIn.nextInt();
if (a == 1) {
System.out.println("\nEnter tournament name");
tournament = keyIn.next();
System.out.println("\nEnter number of players");
number_of_players = keyIn.nextInt();
System.out.println("Enter players");
for (int i = 0; i < number_of_players; i++) {
String name = keyIn.next();
player plr = new player();
plr.setName(name);
players.add(plr);
}
System.out.println("\nEnter places for");
System.out.println(players);
for (int i = 0; i < players.size(); i++) {
System.out.println("\n" + players.get(i));
int places = keyIn.nextInt();
placeDisplay placer = new placeDisplay();
placer.setPlace(places);
placeVar.add(placer);
}
Collections.sort(sort);
System.out.println("\nThe Places are as follows");
for (int i = 0; i < players.size() && i < placeVar.size(); i++) {
System.out.println(placeVar.get(i) + ":" + players.get(i));
}
}
}
here is my public placeDisplay class file.
public class placeDisplay implements Comparable<placeDisplay> {
private int places;
public void setPlace(int nPlace) {
places = nPlace;
}
public int getPlace() {
return places;
}
#Override
public String toString() {
return Integer.toString(places);
}
#Override
public int compareTo(placeDisplay placeDisplay){
if (places > places)
return 1;
else if (places == places)
return 0;
else
return -1;
}
}
Here is the public class file
public class player {
private String name;
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
#Override
public String toString() {
return name;
}
}
and here is my result on this portion of the program. Hope you guys can help me out on this one!
1:Add a tournament 2:View Existing
1
Enter tournament name
tournament1
Enter number of players
3
Enter players
Bob
Sally
John
Enter places for
[Bob, Sally, John]
Bob
2
Sally
1
John
3
The Places are as follows
2:Bob
1:Sally
3:John
Return to Main Menu? (Y/N)
Need to Modify your comparator method.
public int compareTo(placeDisplay placeDisplay){
if (places > placeDisplay.places)
return 1;
else if (places == placeDisplay.places)
return 0;
else
return -1;
}
Your compareTo is not right because you are comparing the same variable.
Change it to:
#Override
public int compareTo(placeDisplay placeDisplay){
if (places > placeDisplay.getPlace())
return 1;
else if (places == placeDisplay.getPlace())
return 0;
else
return -1;
}
Or even simply:
#Override
public int compareTo(placeDisplay placeDisplay){
return places - placeDisplay.getPlace();
}
I also suggest you to overwrite the equals method to make it consistent with your compareTo, as recommended in the Comparable interface documentation: "The natural ordering for a class C is said to be consistent with equals if and only if e1.compareTo(e2) == 0 has the same boolean value as e1.equals(e2) for every e1 and e2 of class C. Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.".
Im having a class Woning (house) and a subclass KoopWoning (buyable House) and a subclass HuurWoning (rentable House). KoopWoning and Huurwoning extend Woning. HuurWoning is just a Woning, whereas KoopWoning has an extra variable energylevel. KoopWoning has also a function getEnergylevel, which returns the energylevel of the KoopWoning. I also have a class Portefeuille which has an arraylist of Woningen.
Im reading all Woningen in a Portefeuille from a textfile. In a 5th class, I want to be able to sort the ArrayList of Woningen of Portefeuille (from the textfile). I have a function woningenTot(int maxprijs) which returns an ArrayList with all the Woningen that fullfil the requirement (having a price below maxprijs). These Woningen I want to print on the screen.
The problem is as follows:
It can be possible that there is also a KoopWoning in the file. In that case I also want to be able to sort on energylevel. However, I can't sort on the energylevels. I can't call the function getEnergylevel because it's an ArrayList, and Woning doesn't contain the function getEnergylevel.
So how can I solve this? If it's too vague, I could include the code, however it's quite big :O
Any help is appreciated; i have spent a couple of hours on this program, from which at least 1.5 hours on this problem alone :(
EDIT: Here is the code for class KoopWoning
public class KoopWoning extends Woning implements EnergiepeilWoning {
private char energiepeil;
public KoopWoning (Adres adres, int kamers, int vraagPrijs, char energiepeil) {
super(adres, kamers, vraagPrijs);
this.energiepeil = energiepeil;
}
public char getEnergiepeil () {
return energiepeil;
}
public boolean compareEnergiepeil (Object other) {
boolean res = false;
if (other instanceof KoopWoning) {
KoopWoning that = (KoopWoning) other;
res = (this.getEnergiepeil() == that.getEnergiepeil());
}
return res;
}
public String toString () {
String res = adres + ", " + kamers + " kamers, prijs " + prijs + ", energiepeil " + energiepeil;
return res;
}
And here is the code for class Woning
public class Woning {
protected int kamers;
protected int prijs;
protected Adres adres;
protected String tag;
public Woning (Adres adres, int kamers, int prijs) {
this.adres = adres;
this.kamers = kamers;
this.prijs = prijs;
}
public String toString () {
String res = adres + ", " + kamers + " kamers, prijs " + prijs;
return res;
}
public void setTag (String tag) {
this.tag = tag;
}
public String getTag () {
return tag;
}
public boolean kostHooguit (int maxprijs) {
return (prijs <= maxprijs);
}
public boolean equals (Object other) {
boolean res = false;
if (other instanceof Woning) {
Woning that = (Woning) other;
if (this.adres.equals(that.adres))
res = true;
}
return res;
}
public static Woning read (Scanner sc) {
try {
Adres adress = Adres.read(sc);
int kamer = sc.nextInt();
sc.next();
sc.next();
int prijs = sc.nextInt();
String check = sc.next();
if (check.equals("energiepeil")) {
char peil = sc.next().charAt(0);
KoopWoning kwoning = new KoopWoning (adress, kamer, prijs, peil);
return kwoning;
}
else {
Woning woning = new Woning (adress, kamer, prijs);
return woning;
}
}
catch (Exception e) {
System.out.println("Woning: Exception is caught");
System.out.println(e.getMessage());
Adres adress = new Adres ("", "", "", "");
Woning woning = new Woning (adress, 0, 0);
return woning;
}
}
}
And lastly, the code for the class Portefeuille
public class Portefeuille {
private ArrayList<Woning> woninglijst;
public Portefeuille () {
woninglijst = new ArrayList<Woning>();
}
public void voegToe (Woning woning) {
if (!woninglijst.contains(woning))
woninglijst.add(woning);
}
public ArrayList<Woning> woningenTot (int maxprijs) {
ArrayList<Woning> woninglijst2 = new ArrayList<Woning>();
for (int i = 0; i < woninglijst.size(); i++) {
if(woninglijst.get(i).kostHooguit(maxprijs))
woninglijst2.add(woninglijst.get(i));
}
return woninglijst2;
}
public String toStringExt () {
String res = "[";
for (int i = 0; i < woninglijst.size(); i++)
res = res + woninglijst.get(i).toString() + "; ";
if (woninglijst.size() != 0)
res = res.substring (0, res.length() - 2);
res = res + "]";
return res;
}
public String toString () {
String res = "";
for (int i = 0; i < woninglijst.size(); i++)
res = woninglijst.get(i).toString2();
return res;
}
public boolean equals (Object other) {
boolean res = false;
if (other instanceof Portefeuille) {
Portefeuille that = (Portefeuille) other;
if (this.woninglijst.size() == that.woninglijst.size()) {
int i = 0;
while (i < this.woninglijst.size() && this.woninglijst.get(i).equals(that.woninglijst.get(i)))
i = i + 1;
res = (i == this.woninglijst.size());
}
}
return res;
}
public static Portefeuille read (String infile) {
try {
Scanner sc = new Scanner (new File(infile));
ArrayList<Woning> wlijst = new ArrayList<Woning>();
Portefeuille p = new Portefeuille();
int woningen = sc.nextInt();
int i = 0;
while (i < woningen) {
sc.nextLine();
String tag = sc.nextLine();
wlijst.add(Woning.read(sc));
p.voegToe(wlijst.get(i));
i++;
}
sc.close();
return p;
}
catch (Exception e) {
System.out.println("Portefeuille: Exception is caught");
Portefeuille p = new Portefeuille();
return p;
}
}
}
EDIT
I fixed it myself. Thanks for answering you all :)
You could define, on the top-level class, a method like getSortableValue(), and implement it to return a default field (you didn't mention the field you need to sort on for Woningen). In the KoopWoning you override this method to return the energyLevel instead. Then you always sort on the value returned by getSortableValue().
You can let the them implement Comparable, so like Woning implements Comparable<Woning>. This will let you implement the (required) method:
#override
public int compareTo(Woning other) {
int result = Integer.compareto(maxPrijs, other.maxPrijs);
if (result != 0) return result;
result = Integer.compareto(someField, other.someField);
if (result != 0) return result;
// etc...
return 0;
}
The subclass KoopWoning extends Woning implements Comparable<KoopWoning> can have a method like this:
#override
public int compareTo(KoopWoning other) {
int result = Integer.compareto(energylevel, other.energylevel);
if (result != 0) return result;
return super.compareTo(other);
}
Then all you need to do is load all the Woning instances in a list and execute
Collections.sort(list);
Having subclasses inherit Comparable is optional, so HuurWoning will just sort like Woning.
You could define a Comparator on Woning that determines the relative ordering of two Woning. You could do this either by having a method that looks at the actual types of the two arguments and then acts appropriately, or, better, by having an overrideable method of Woning that returns some value that you can use for sorting purposes.
If, for instance, you decide that anything with an energy level should come after anything without one, then you can have KoopWoning return something with the energy level in the high order bits of a long, so that it always comes out higher than anything without one (essentially you'd be setting a default energy level of zero).
Then, you can use
Collections.sort(arrayList, myComparator);
to sort the list based on the Comparator you've created.
There are some nice classes in the Guava library that help with Comparator building on multiple keys, but if your case is fairly simple, you probably won't need them.
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.
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.