Static Method Java confusion - java

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.

Related

How do i compare the values of objects in an object array?

My code outputs this:
Computer 1 bets 5
Computer 2 bets 8
Computer 3 bets 4
Computer 4 bets 3
Computer 5 bets 8
I want to make a method "displayWinners()" that compares the bet value of all the objects in this array and returns all of the object id's with the highest bet value, in this case it would be Computer 2 and 5 with a bet of 8. How would i do that?
public class Computer {
Computer[] c;
private int id;
private int bet;
public void create(int numComps) {
int i;
c = new Computer[numComps];
for (i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i+1;
c[i].bet = bet();
c[i].display();
}
displayWinners();
}
public int bet() {
return (int) (Math.random() * 10) + 1;
}
public void display() {
String name = "Computer " + id;
System.out.println(name + " bets " + bet);
}
public void displayWinners() {
System.out.println();
}
public static void main(String[] args) {
Computer c = new Computer();
c.create(5);
}
}
why don't you allocate a variable for an index of the maximum value and a value itself, and keep checking & rewriting the variable as function bet() is executed.
the code below is not properly verified but just have a look over.
public class Computer {
Computer[] c;
private int id;
private int bet;
private List<Integer> maxId;
private int maxBet;
public void create(int numComps) {
int i;
c = new Computer[numComps];
maxId = new ArrayList<Integer>();
maxBet = 0;
for (i = 0; i < numComps; i++) {
c[i] = new Computer();
c[i].id = i+1;
c[i].bet = bet();
c[i].display();
if(c[i].bet > maxBet) {
maxId = new ArrayList<Integer>();
maxId.add(c[i].id);
maxBet = c[i].bet;
}
else if(c[i].bet == maxBet) {
maxId.add(c[i].id);
}
}
displayWinners();
}
public int bet() {
return (int) (Math.random() * 10) + 1;
}
public void display() {
String name = "Computer " + id;
System.out.println(name + " bets " + bet);
}
public void displayWinners() {
System.out.format("Computer %d", maxId.get(0));
if(maxId.size() > 1) {
for(int i=1; i<maxId.size(); i++) {
System.out.format(" and %d", maxId.get(i));
}
}
System.out.format(" with a bet of %d\n", maxBet);
}
public static void main(String[] args) {
Computer c = new Computer();
c.create(5);
}
}
Ok, just for the fun to provide this with a small trick.
You just iterate your array.
Then, I will compare the current bet with the maximum value known using Integer.compare and base on the result, I will either:
r > 0 - clear the list and add the instance to the list
r == 0 - Add the instance to the list
r < 0 - Do nothing
Good to know, the actual value return by the method are simpler [-1, 0, 1], it will matter shortly.
Now, we can see some redondance in adding into the list, to reduce that, we are able to use a switch instead of ifs.
List<Computer> winners = new ArrayList<Computer>();
for ( Computer c : computers ){
int r = Integer.compare(c.getBet(), maxBet);
switch(r){
case 1: //Current bet is higher
maxIds.clear();
maxBet = c.getBet();
case 0: //Current bet is equals
winners.add(c);
case -1: //Current bet is lower (optional line, just for the explanation)
}
}
Since I don't use break, after we clear the list, we will add into it.
Note: A fail-safe should be added in case of Integer.compare implementation changes. The documentation state that it will return any value instead of -1, 0 or 1. But the current implementation is simpler :
public static int compare(int x, int y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}
First of all, I recommend you to split storage and business logic. Move all methods for show Computer class out.
So to find the winners you have to do following steps:
Create a list of computers (you can create an array or a list);
Iterate over the collection once to find the highest bet;
Iterate over the collection second time to filter out all computers with the highest bet.
If you ask such question, then I suppose, that no need of you right now to offer different sorting algorithms or special data structures (they all do the same, but much faster for big input data).
This is one of the possible solutions (I tried to keep it simple):
public class Foo {
public static void main(String[] args) throws IOException {
Computer[] computers = createComputer(5);
int highestBet = getHighestBet(computers);
List<Integer> ids = getIdsWithBet(computers, highestBet);
System.out.println(ids.stream().map(String::valueOf).collect(Collectors.joining(",")));
}
private static int getHighestBet(Computer... computers) {
int max = 0;
for (Computer computer : computers)
max = Math.max(max, computer.getBet());
return max;
}
private static List<Integer> getIdsWithBet(Computer[] computers, int bet) {
List<Integer> ids = new ArrayList<>(computers.length);
for (Computer computer : computers)
if (computer.getBet() == bet)
ids.add(computer.getId());
return ids;
}
// you van use List<Computer>
private static Computer[] createComputer(int total) {
Random random = new Random();
Computer[] computers = new Computer[total];
for (int i = 0; i < computers.length; i++) {
computers[i] = new Computer(i + 1, random.nextInt(10) + 1);
System.out.println(computers[i]);
}
return computers;
}
}
// It's better to use unmodifiable objects if you can
final class Computer {
private final int id;
private final int bet;
public Computer(int id, int bet) {
this.id = id;
this.bet = bet;
}
public int getId() {
return id;
}
public int getBet() {
return bet;
}
#Override
public String toString() {
return "Computer " + id + " bets " + bet;
}
}
import java.util.ArrayList at top of file
```
int maxBet = 0;
ArrayList<Integer> maxIds = new ArrayList<Integer>();
// This is a for each loop, it is saying, for each computer in the list of computers
for ( Computer computer : computers ){
/* if that computer has a higher bet than what we previously thought
was the highest, empty our list and set maxBet to that, and add this
computer to the list of computers that have that bet number */
if (computer.getBet() > maxBet){
maxIds.clear();
maxBet = computer.getBet();
maxIds.add(computer.getId());
// another computer has the same max bet value
} else if ( computer.getBet() == maxBet){
maxIds.add(computer.getId());
}
}
System.out.println("Max Bet: " + maxBet);
System.out.print("Computers with max bet: ");
// for each id in our list of computers that have the max bet
for ( int id : maxIds ){
System.out.print(id + " ");
}

static arraylist creating infinite instances of itself

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.

Different variable output from same method JAVA genetic algorithm

So i am trying to build a genetic algorithm on java i stuck on getting
fitness of my population here 3 classes from my project:
Class Individu
public class Individu {
int Popsize=4;
int Health[]= new int[Popsize];
int Attack[]= new int[Popsize];
int Atspeed[]= new int[Popsize];
int Move[]= new int[Popsize];
int health,attack,lifetime,dmgdone,attspeed,range,move;
double fitness;
double Pitness[]= new double[20];
Random random = new Random();
public int setHealth(){
health = random.nextInt(150 - 75) + 75;
return health;
}
public int setAttack(){
attack = random.nextInt(10 - 5) + 10;
return attack;
}
public int setAttspeed(){
attspeed = random.nextInt(3 - 1) + 3;
return attspeed;
}
public int setMoveSpeed(){
move = random.nextInt(8 - 4) + 1;
return move;
}
public int getGeneHealth(int index) {
return Health[index];
}
public int getGeneAttack(int index) {
return Attack[index];
}
public int getGeneAtspedd(int index) {
return Atspeed[index];
}
public int getGeneMove(int index) {
return Move[index];
}
public void setGene(int index, int value) {
Health[index]=value;
Attack[index]=value;
Atspeed[index]=value;
Move[index]=value;
fitness = 0;
}
public int size() {
return Popsize;
}
public double[] GenerateIndividual(){
for (int i = 0; i <Popsize; i++) {
Health[i]=setHealth();
Attack[i]=setAttack();
Atspeed[i]=setAttspeed();
Move[i]=setMoveSpeed();
}
return Pitness;
}
Class Fitness
public class Fitness {
Individu individu= new Individu();
double fitness;
double Pitness[]= new double[20];
public double getFitness(){
individu.GenerateIndividual();
for (int i = 0; i <=3; i++) {
fitness=
individu.getGeneHealth(i)+individu.getGeneAtspedd(i)+
individu.getGeneAttack(i)+
individu.getGeneMove(i));
fitness=fitness/171;
Pitness[i]=fitness;
System.out.println("Health from class
fitness"+individu.Health[i]);
}
return fitness;
}
}
Main Class
public class main {
public static void main(String[] args) {
Individu aaa=new Individu();
Fitness bbb= new Fitness();
bbb.getFitness();
aaa.GenerateIndividual();
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(3);
for (int i=0; i<=3; i++){
//System.out.println("Fitness ");
System.out.println("Generasi ke :"+i+1);
System.out.println("Health "+aaa.getGeneHealth(i));
System.out.println("Attackspeed "+aaa.getGeneAtspedd(i));
System.out.println("Attack "+aaa.getGeneAttack(i));
System.out.println("movementSpeed "+aaa.getGeneMove(i));
}
}
}
What i struggle is when i run this script i got 2 double value from 1 variable first value is from Fitness class as i printed here
System.out.println("Health from class fitness"+individu.Health[i]);
and second variable i printed here from Main Class
System.out.println("Health "+aaa.getGeneHealth(i));
that 2 variable is always have different value causing my fitness and my generation is not correlated each other.
My question is how to make this 2 variable print same value?
Well, aside from the many problems I can detect about the essentials of Genetic Algorithms, I see 'individu' and 'aaa' are two different Java objects.
Individu aaa=new Individu();
aaa.GenerateIndividual();
and
Individu individu= new Individu();
individu.GenerateIndividual();
Since your Health and Fitness are randomly generated on GenerateIndividual(), both 'aaa' and 'individu' will get different Health values.
I strongly recommend you to review GA essentials, since I can see many conception errors in your system.

Online grading says my output values are not correct but I don't see why?

I am doing some homework for my java programming class, but this code is giving me trouble. The online program that grades it says there is a problem with my output, but I really don't see why. Can anyone help?
The assignment:
Write a class named Car that has the following fields:
yearModel: The yearModel field is an int that holds the car's year model.
make: The make field is a String object that holds the make of the car.
speed: The speed field is an int that holds the car's current speed.
In addition, the class should have the following methods :
Constructor : The constructor should accept the car's year model and make as arguments .
These values should be assigned to the object 's yearModel and make fields. The
constructor should also assign 0 to the speed field.
Accessor: The appropriate accessor methods should be implemented to access the values
stored in the object 's yearModel, make, and speed fields.
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
Demonstrate the class in a program that contains a Car object , and then calls the
accelerate method five times. After each call to the accelerate method , get the current
speed of the car and print it on a separate line. Then, call the brake method five times,
each time printing the current speed of the car on a separate line.
My code:
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int model, String m) {
yearModel = model;
make = m;
speed = 0;
}
public int getYearModel() {
return yearModel;
}
public String getMake() {
return make;
}
public int getSpeed() {
return speed;
}
public int accelerate() {
speed += 5;
return speed;
}
public int brake(int b) {
b -= 5;
return b;
}
}
class CarDemo {
public static void main(String[] args) {
Car c = new Car(1992, "Mustang");
int s = 0;
s = c.getSpeed();
for(int i = 0; i < 5; i++) {
System.out.println("The " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
s = c.accelerate();
System.out.println("Now the " + c.getYearModel() + " " + c.getMake() + "is going: " + s);
}
}
}
Edit:
Based on the suggestions below, I have edited my code to the following; however, the system still says that my output is incorrect.
public class Car{
private int yearModel;
private String make;
private int speed;
public Car(int y, String m){
yearModel = y;
make = m;
speed = 0;
}
public int getYearModel(){
return yearModel;
}
public String getMake(){
return make;
}
public int getSpeed(){
return speed;
}
public void accelerate(){
speed += 5;
}
public void brake(){
speed -= 5;
}
}
class CarDemo{
public static void main(String[] args){
Car theCar = new Car(2010, "Porsch");
for(int i = 0; i < 5; i++){
theCar.accelerate();
System.out.println(theCar.getSpeed());
}
for(int count = 0; count < 5; count++){
theCar.brake();
System.out.println(theCar.getSpeed());
}
}
}
for brake you need to do speed -= 5, not b -= 5. Also I do not think the brake method needs an input argument.
In addition you accelerate 5 times but never brake
Your main issue is the brake method. The requirements state that it should subtract 5 from the current speed. So, you should make it like your accelerate method, but subtracting 5 instead of adding. It shouldn't take in a parameter.
Also, I don't know if this would cause an issue, but your accelerate and brake methods shouldn't return the speed, according to the requirements. Change their return types to void, and remove the return statements.
Lastly, You test main doesn't do exactly what the requirements say to do. Read it carefully to see what it should do, and do EXACTLY what it says.
Follow the specification.
The spec says:
accelerate: The accelerate method should add 5 to the speed field when it is called.
brake: The brake method should subtract 5 from the speed field each time it is called.
These 2 methods have no return type and take no arguments.
So, they should be:
public void accelerate() {
speed += 5;
}
// brake should not take an argument
public void brake() {
// this should be speed, not b
speed -= 5;
}
Additionally, your demo should follow the spec (in comments):
class CarDemo {
public static void main(String[] args) {
//Demonstrate the class in a program that contains a Car object
Car c = new Car(1992, "Mustang");
for (int i = 0; i < 5; i++) {
//and then calls the accelerate method five times.
c.accelerate();
//After each call to the accelerate method, get the current speed of the car and print it on a separate line.
System.out.println(c.getSpeed());
}
for (int i = 0; i < 5; i++) {
//Then, call the brake method five times,
c.brake();
//each time printing the current speed of the car on a separate line.
System.out.println(c.getSpeed());
}
}
}
When working off of a well-written, explicit specification as has been provided for your assignment, it can be very helpful to do what I've done above--include the spec as comments and fill in the code around them.
You're printing The " + c.getYearModel() + " " + c.getMake() + "is going: " + s 5 times. You should put that outside the loop so it's printed once only.
IMHO I don't think you need to be returning the speed from the accelerate() function either. I'd suggest making that a void function and using the getSpeed() method instead of assigning to an intermediate variable.
I am currently taking the Prog Fund I & II class. If you are using Pearson, then this should help. I had the answer correct the first time. You just have to format it correctly in the proper order as so.
import java.util.Scanner;
public class Car
{
private int yearModel; // Holds the car's year model
private String make; // Holds the make of the car
private int speed; // Holds the car's current speed
public static void main(String[] args)
{
// Creates car object
Car vehicle = new Car(2018, "Barbie Mobile");
// Creates object for user input
Scanner keyboard = new Scanner(System.in);
// Holds the speed of the car
int speed = 0;
// Calls accelerate 5 times
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.accelerate();
speed = vehicle.getSpeed();
System.out.println(speed);
// Calls break 5 times
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
vehicle.brake();
speed = vehicle.getSpeed();
System.out.println(speed);
}
public Car(int year, String maker)
{
// Assigns values to car's year model and make
yearModel = year;
make = maker;
// Assigns 0 to the speed field
speed = 0;
}
/* #return gets year model */
public int getYearModel()
{
return yearModel;
}
/* #return The speed */
public int getSpeed()
{
return speed;
}
/* #return Gets the making of car */
public String getMake()
{
return make;
}
/* Adds 5 to speed when called */
public void accelerate()
{
speed += 5;
}
/* Subtracts 5 from speed when called */
public void brake()
{
speed -= 5;
}
}
I am taking the same class right now, using Pearson Revel. If anyone else comes across this problem, this should help.. Spoiler alert, I will be posting the answer to the problem below
Pearson Revel is such a pain in the butt, they do a horrible job describing how they want the programs structured and output displayed, and if anything is off by even one space or something similar, you lose all points. That being said, the problem demonstrates the calling of the program under "Sample Run" as java Car. So it sounds like the main program that creates a Car object and calls all of it's methods is within the same class (test it out in a text editor, you'll see that if you create a seperate class under the Car class and call Car.java from the command line, it will throw an error; stating the class Car does not have a main. So therefore, it's safe to say you need to create the main method inside of the Car class (wish they would just say that, right?).
Here is my graded & passing answer.
public class Car {
private int yearModel;
private String make;
private int speed;
public Car(int year, String make) {
this.yearModel = year;
this.make = make;
this.speed = 0;
}
public void brake() {
this.speed -= 5;
}
public void accelerate() {
this.speed += 5;
}
public int getSpeed() {
return this.speed;
}
public String getMake() {
return this.make;
}
public int getYearModel() {
return this.yearModel;
}
public static void main(String[] args) {
Car myCar = new Car(2019, "Tacoma");
for (int i=0;i < 5;i++) {
myCar.accelerate();
System.out.println(myCar.getSpeed());
}
for (int i=0;i < 5;i++) {
myCar.brake();
System.out.println(myCar.getSpeed());
}
}
}
And here is Revel's suggested answer after completion
public class Car {
public static void main(String[] args) {
Car batmobile = new Car(1965, "Bat Mobile");
for(int i=0; i<5; i++){
batmobile.accelerate();
System.out.println(batmobile.getSpeed());
}
for(int i=0; i<5; i++){
batmobile.brake();
System.out.println(batmobile.getSpeed());
}
}
private int yearModel;
private String make;
private int speed;
public Car(int yearModel, String make){
this.yearModel = yearModel;
this.make = make;
this.speed = 0;
}
public int getYearModel(){
return this.yearModel;
}
public String getMake(){
return this.make;
}
public int getSpeed(){
return this.speed;
}
public void accelerate(){
this.speed += 5;
}
public void brake(){
this.speed -= 5;
}
}

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