I'm a student and, yes, this is my homework. I've spent the last week reviewing notes, reading the book, and researching related topics on the net, but I just don't get what the problem is. Can you tell me what I'm doing wrong? Any help will be greatly appreciated. (I'm only using notepad and the command prompt.)
The guidelines I was given: Create a Java application consisting of two classes. Class one will be your application class. Class two will be a class called Car. Your application will create an instance of Car, called nova, and drive it.
Rules for the car:
You can’t drive a car if it is not started (send an error message to the console).
You can’t stop a car if it is not started (send an error message to the console).
You can’t start a car if it is already started (send an error message to the console).
Once you tell the car to drive, the only thing you can do is stop (Send a message to the console)
Once you call stop, the car will return to the initial state and the user must start the car before attempting to do any other functions. (Send a message to the console)
The purpose of the showState method is provide a way to inspect the state of the car. It should build a message, which can then be sent to the console.
My code:
public class MyAppAssignment3
{
public static void main (String[] args)
{
System.out.println("Scenario 1");
Car nova1 = new Car();
nova1.start();
nova1.showState();
nova1.drive();
nova1.stop();
nova1.showState();
System.out.println("");
System.out.println("Scenario 2");
Car nova2 = new Car();
nova2.showState();
nova2.drive(); //needs to send error message - can't drive a car that's not started
nova2.stop();
nova2.showState();
System.out.println("");
System.out.println("Scenario 3");
Car nova3 = new Car();
nova3.showState();
nova3.start();
nova3.showState();
nova3.stop(); //needs to send error message - can't stop a car that's not driving
nova3.showState();
nova3.drive();
nova3.stop();
}
}
class Car
{
private boolean isStarted;
private boolean isDriving;
private boolean isStopped;
private String showState;
public Car()
{
this.showState = showState;
}
public void start()
{
isStarted = true;
isDriving = false;
isStopped = false;
System.out.println("The car is " + this.showState);
}
public void drive()
{
isStarted = false;
isStopped = false;
isDriving = true;
System.out.println("The car is " + this.showState);
}
public void stop()
{
isStopped = true;
isStarted = false;
isDriving = false;
System.out.println("The car is " + this.showState);
}
public String showState()
{
if (isStarted)
{
showState = "started";
}
else if(isDriving)
{
showState = "driving";
}
else if(isStopped)
{
showState = "stopped";
}
System.out.println("The car is " + this.showState);
return showState;
}
}
My output (which is all wrong - the values are incorrect):
Scenario 1
The car is null
The car is started
The car is started
The car is started
The car is stopped
Scenario 2
The car is null
The car is null
The car is null
The car is stopped
Scenario 3
The car is null
The car is null
The car is started
The car is started
The car is stopped
The car is stopped
The car is stopped
Sorry if this posted all wonky. I typed it fine but the preview looks screwy.
This isn't actually doing anything...
public Car()
{
this.showState = showState;
}
Basically, it's simply reassign the same value back to itself. I'd change to an initial state, probably of stopped
I'd use enum for my car status, rather then relying on boolean states, which could become jumbled...
public enum CarState {
Stopped,
Started,
Driving
}
Then simply assign it to a single state variable...
class Car
{
private CarState state;
public Car()
{
this.state= CarState.Stopped;
}
public void start()
{
if (state.equals(State.Stopped)) {
state = CarState.Started;
showState();
} else {
System.error.println("Car is not in a valid state to be started");
}
}
public void drive()
{
if (state.equals(State.Started)) {
state = CarState.Driving;
showState();
} else {
System.error.println("Car is not in a valid state to be driven");
}
}
public void stop()
{
if (state.equals(State.Driving)) {
state = CarState.Stopped;
showState();
} else {
System.error.println("Car is not in a valid state to be stopped");
}
}
public String showState()
{
System.out.println("The car is " + state);
}
}
The other issue you're having is that the showStatus isn't been called when you change state, which isn't assigning the current state to the showState variable...which I've corrected for by using enum
For one you're just creating a new instance. You never actually set defaults for those instances.
Consider at least something like this:
public Car()
{
isStopped = true;
}
That way when you call your first nova1.start(); you can check if isStopped is true before allowing it to start again...
public void start()
{
if(isStopped)
{
isStarted = true;
isDriving = false;
isStopped = false;
showState = "started";
System.out.println("The car is " + this.showState);
}
}
Just one example. But you can easily use that to extrapolate the rest of your needs. My point is primarily that you create an instance but then expect the boolean values to have a value without being specified. You can do this in defaults, or in the constructor.
For example:
private boolean isStarted = false;
Using enum's is a nice idea.
Here is an Implementation using Enum's, Enum's with default Implementations and own implementations using the typesystem.
Also there aren't any Conditionals, like if or switch used.
Just pure and beautiful Java Code.
public class Car {
private enum State {
OFF {
void start(Car c) {
System.out.println("Starting the car");
c.state = State.STARTED;
}
},
STARTED {
void stop(Car c) {
System.out.println("Stopping the car");
c.state = State.OFF;
}
void drive(Car c) {
System.out.println("Driving the car");
c.state = State.DRIVING;
}
},
DRIVING {
void stop (Car c) {
System.out.println("Stopping the car");
c.state = State.OFF;
}
};
void start(Car c) {
System.err.println("Can't start");
}
void stop(Car c) {
System.err.println("Can't stop");
}
void drive(Car c) {
System.err.println("Can't drive");
}
}
private State state = State.OFF;
public void start(){
state.start(this);
}
public void stop(){
state.stop(this);
}
public void drive() {
state.drive(this);
}
public void showState(){
System.out.println("The car is "+state);
}
}
This worked! Thanks for all the help!
public class MyAppAssignment3
{
public static void main (String[] args)
{
System.out.println("Scenario 1");
Car nova1 = new Car();
nova1.start();
nova1.showState();
nova1.drive();
nova1.stop();
nova1.showState();
System.out.println("");
System.out.println("Scenario 2");
Car nova2 = new Car();
nova2.showState();
nova2.drive();
nova2.stop();
nova2.showState();
System.out.println("");
System.out.println("Scenario 3");
Car nova3 = new Car();
nova3.showState();
nova3.start();
nova3.showState();
nova3.stop();
nova3.showState();
nova3.drive();
nova3.stop();
}
}
class Car
{
private boolean isStarted;
private boolean isDriving;
private boolean isStopped;
private String showState;
public Car()
{
isStarted = false;
isDriving = false;
isStopped = true;
}
public void start()
{
if(isStarted == false)
{
isStopped = false;
isStarted = true;
showState();
}
else
{
System.out.println("You can't start a car which is already started.");
}
}
public void drive()
{
if(isStarted)
{
isDriving = true;
showState();
}
else
{
System.out.println("You can't drive a car which is not started.");
}
}
public void stop()
{
if(isStarted)
{
isStarted = false;
isDriving = false;
isStopped = true;
showState();
}
else
{
System.out.println("You can't stop a car which is not started.");
}
}
public String showState()
{
if(isStarted && (isDriving == false))
{
showState = "started";
}
else if(isStarted && isDriving)
{
showState = "driving";
}
else if(isStopped)
{
showState = "stopped";
}
System.out.println("The car is " + this.showState + ".");
return showState;
}
}
What I would suggest is this, each car has its own unique id:
class Car
{
private boolean isStarted;
private boolean isDriving;
private boolean isStopped;
private String showState;
private int id;
public Car(Integer id)
{
this.id = id;
}
...
}
then in all place where you say print out, also include id:
System.out.println("The car id "+id+" is "+ this.showState);
then create an object like that:
Car nova1 = new Car(1);
Car nova2 = new Car(2);
Car nova3 = new Car(3);
It is not solution, but it gives the way to solution. You will find solution and u will feel it's taste
You have to translate in code what you've been asked for, and as you can see it's even way close to actual requirement - e.g.:
You can’t drive a car if it is not started (send an error message to the console).
becomes:
public void drive()
{
if( this.isStarted == false ){
System.out.println("You should start the car first!");
}else{
System.out.println("Car is running!");
}
}
Notice that you can write !this.isStarted as a shorthand for isStarted == false.
Try outputting the value of variables in each step. There are a few issues in the logical flow. For example, check the constructor.
public Car()
{
System.out.println(showState);
this.showState = showState;
}
There is no showState value being passed to the constructor and its not initialized inside the function too.
Also, inside each function start, stop and drive, you need to write :
System.out.println("The car is " + this.showState());
instead of :
System.out.println("The car is " + this.showState);
Let's keep it simple, why use 3 variables when you need only two? Correct if I'm wrong, but if a car is not started and you are not driving it then it's stopped, right? Look at my class:
public class car
{
private boolean isStarted;
private boolean isDriving;
public car()
{
isStarted = false;
isDriving = false;
//Initial State
showState();
}
public void start()
{
if(!isStarted)
{
if(!isDriving)
isStarted = true;
}
else
System.err.println("You can\'t start a car which is already started"); //You can’t start a car if it is already started (send an error message to the console).
showState();
}
public void drive()
{
if(isStarted)
isDriving = true;
else
System.err.println("You can\'t drive a car which is not started");
showState();
}
public void stop()
{
if(isStarted)
{
isStarted = false;
isDriving = false;
// Once you call stop, the car will return to the initial state and the user must start the car before attempting to do any other functions. (Send a message to the console. (Below on ShowState)
}
else
System.err.println("You can\'t stop a car which is not started"); // You can’t stop a car if it is not started (send an error message to the console).
showState(); // Once you tell the car to drive, the only thing you can do is stop (Send a message to the console)
}
public void showState()
{
if(isStarted && isDriving)
System.out.println("It\'s Driving");
if(!isStarted && !isDriving)
System.out.println("It\'s Stopped");
if(isStarted && !isDriving)
System.out.println("It\'s Started");
}
}
I hoped it helped. Cheers
Related
Hello friends I am trying to build a class Car for a project. There are many methods inside the following code as well as an if statement that I am having trouble building, consider the following code
public class Car extends Vehicle {
private boolean isDriving;
private final int horsepower;
private boolean needsMaintenance = false;
private int tripsSinceMaintenance = 0;
Car() {
super();
this.horsepower = 0;
this.isDriving = false;
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
public int getHorsepower() {
return this.horsepower;
}
public boolean getDrive() {
return this.isDriving;
}
public boolean getMain() {
return this.needsMaintenance;
}
public int getTRIP() {
return this.tripsSinceMaintenance;
}
public void drive() {
this.isDriving = true;
}
public void stop() {
this.isDriving = false;
}
public void repair() {
this.needsMaintenance = false;
this.tripsSinceMaintenance = 0;
}
/**
* #param args
*/
public static void main(String[] args) {
Car auto = new Car();
auto.drive();
auto.stop();
if (auto.isDriving == true) {
if (auto.isDriving == false)
auto.tripsSinceMaintenance = auto.tripsSinceMaintenance + 1;
}
if (auto.tripsSinceMaintenance > 100)
auto.needsMaintenance = true;
System.out.println("Drive: " + auto.getDrive());
System.out.println("trip: " + auto.getTRIP());
}
}
What I want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenanceis greater than 100,needsMaintenanceshould becometrue`.
here I expected trips to be 1 but the result is the following:
Drive: false
trip: 0
I have tried this.isDriving==true; and basicaly wherever auto is inside the if statement I put this but the following error appears
non static variable cannot be referenced from static context
help me please!
What i want to do is whenever the attribute isDriving goes from true to false the tripsSinceMaintenance should increase by 1 and also when tripsSinceMaintenance is greater than 100 needsMaintenance should become true
Do this inside stop() method
fun stop() {
if (isDriving) {
tripsSinceMaintenance++;
}
if (tripsSinceMaintenance > 100) {
needsMaintenance = true;
}
isDriving = false;
}
You don't need to put == true inside of an if statement, it's doing that already,
if(someCondition) { // <-- this executes if the condition is true.
Also, you have conflicting conditions nested, meaning...
if (thisIsTrue) {
if (!thisIsTrue) {
// <--- unreachable statements
where you should be incrementing your variable is where you're setting "isDriving = true"
So your code would look like this:
public void drive() {
this.isDriving=true;
auto.tripsSinceMaintenance++;
}
I have an application that I have been working on for a little while, I understand a little of Java.
The scope of the application is combine multiple design patterns in a way that allows reusability, which code can be edited without having to scroll through hundreds of lines of code.
I have implemented a true Singleton Player class.
I have also implemented a decorator weapon class.
I am not looking to add a state pattern for the player class, an example of this would be AliveState and DeadState. Something simple so I understand the workings of it all.
For the sake of this I will post the full PlayerSingleton class:
public class PlayerSingleton{
private static PlayerSingleton player;
Scanner scanner = new Scanner(System.in);
private String playerName;
private Integer playerHealth;
private Weapon weapon;
private PlayerSingleton(Weapon weapon, String pName, int pHealth) {
this.weapon = weapon;
playerName = pName;
playerHealth = pHealth;
}
public static Weapon chooseWeapon(String choice) {
switch (choice) {
case "MP5":
System.out.println("You have chosen MP5!");
return new MP5Weapon();
case "SNIPER":
System.out.println("You have chosen Sniper!");
return new SniperRifleWeapon();
case "SHOTGUN":
System.out.println("You have chosen Shotgun!");
return new ShotgunWeapon();
default:
System.out.println("No gun by that name found!");
return null;
}
}
public static PlayerSingleton getInstance(String choice, String name, int health) {
System.out.println("Choose Weapon to play the with: ");
Weapon weapon = PlayerSingleton.chooseWeapon(choice);
weapon.getDescription();
if (player == null) {
player = new PlayerSingleton(weapon, name, health);
}
return player;
}
public void getWeaponDamage(Weapon damage) {
System.out.println("Damage of weapon: " + weapon.damage());
}
public void attackState(double damage) {
damage = player.weapon.damage();
}
// #Override
// public void aliveState() {
// if(playerHealth >= 1){
//
// }
// }
// #Override
// public void deadState() {
// if(playerHealth ==0){
// System.out.println("You are dead");
// System.out.println("GameOver");
// }
// }
public void chosenWeapon() {
System.out.println("Player Info: " + playerName + " " + "Has: " + playerHealth + " health");
System.out.println(weapon.getDescription() + ":" + " base damage: " + weapon.damage());
}
public void addBasicAttachment(String attachment) {
switch (attachment) {
case "SIGHT":
weapon = new BasicSight(weapon);
break;
case "SILENCER":
weapon = new BasicSilencer(weapon);
break;
case "STOCK":
weapon = new BasicStock(weapon);
break;
default:
System.out.println("No Attachment found!");
}
}
I've tried to implement this with help of Head first design patterns (State) but using the Singleton Pattern on the player class means that I cannot call the object from another class.
public class DeadState implements PlayerState{
PlayerSingleton player;
public DeadState(PlayerSingleton player){
this.player = player;
}
#Override
public void deadState() {
System.out.println("You are Dead!");
}
#Override
public void aliveState() {
System.out.println("You are Dead!");
}
}
Above is a test on making a DeadState implementing from a PlayerState interface.
Is there any way to do this with separate classes using the state pattern with PlayerSingleton?
Seriously any help would be amazing!
Also if you could explain the answer so I understand better.
First of all about this sentence that you said:
using the Singleton Pattern on the player class means that I cannot call the object from another class.
Actually you can call the object from other classes, as long as you have access to the instance, and that's how state pattern works.
I took your classes and remove some code just for the sake of simplicity and explain better the solution, you can add back the parts of the code I removed if you use this solution:
I used the two states you have in your code, first this is the PlayerState interface, it has two methods, one for taking damage and other for respawning:
public interface PlayerState {
void respawn();
void takeDamage(int damage);
}
Then the implementation of Alive state has only implementation for the takeDamage method, which receives the amount of damage taken:
public class AliveState implements PlayerState {
private PlayerSingleton player;
public AliveState(PlayerSingleton player) {
this.player = player;
this.player.setHealth(PlayerSingleton.MAX_PLAYER_HEALTH);
}
#Override
public void takeDamage(int damage) {
System.out.println(String.format("Suffering %d damage!", damage));
player.setHealth(player.getHealth() - damage);
if (player.getHealth() <= 0) {
player.setLives(player.getLives() - 1);
player.setState(new DeadState(player));
}
}
#Override
public void respawn() {
System.out.println("Nothing to do, player is alive!");
}
}
Same for the implementation of the DeadState, which has only implementation for the respawn method, as long as the player has lives left:
public class DeadState implements PlayerState {
private PlayerSingleton player;
public DeadState(PlayerSingleton player) {
this.player = player;
}
#Override
public void takeDamage(int damage) {
System.out.println("Nothing to do, player is dead!");
}
#Override
public void respawn() {
if (player.getLives() > 0) {
System.out.println("respawning to start location!");
player.setState(new AliveState(player));
} else {
System.out.println("Game Over!");
}
}
}
And finally the PlayerSingleton class, which is assigned the state AliveState when the player is created, the takeDamage and respawn methods call the implementations in the current player's state, and if you noticed, the State implementations have a reference to the player's instance, so they can change the object state.
public class PlayerSingleton {
public static Integer MAX_PLAYER_HEALTH = 500;
public static Integer DEFAULT_PLAYER_LIVES = 2;
private static PlayerSingleton player;
private Integer health = MAX_PLAYER_HEALTH;
private int lives = DEFAULT_PLAYER_LIVES;
private PlayerState playerState;
private PlayerSingleton() {
setState(new AliveState(this));
}
public static PlayerSingleton getInstance() {
if (player == null) {
player = new PlayerSingleton();
}
return player;
}
public void sufferDamage(int damage) {
playerState.takeDamage(damage);
}
public void respawn(String location) {
playerState.respawn();
}
// Getters and Setters
}
I used the following main method to test:
public static void main(String[] args) {
PlayerSingleton playerSingleton = PlayerSingleton.getInstance();
playerSingleton.takeDamage(300);
playerSingleton.respawn();
playerSingleton.takeDamage(300);
playerSingleton.respawn();
playerSingleton.takeDamage(600);
playerSingleton.respawn();
}
And this was the output:
Suffering 300 damage!
Nothing to do, player is alive!
Suffering 300 damage!
Player is dead!
respawning to start location!
Suffering 600 damage!
Player is dead!
Game Over!
I am trying to take a 3 class program and pass a boolean for reserving a room. I have driver program, building, room programs. I set the reserve to false and I can't figure out how to print out a text statement when it's already set to true. I think I am either doing the passing of the boolean through the classes from the driver wrong or missing something. I have played with reserveRoom in building class with an if statement to see if it's already true to print a statement and no matter which way I go it doesn't work.
Any help would be appreciated.
Thank you.
From my driver program that sends the boolean to the building program
System.out.print ("Which room would you like to reserve?");
System.out.print (building);
System.out.print ("reserve: ");
reservNum = input.nextInt();
building.reserveRoom(reserve, reservNum);
From my building class.
public void reserveRoom (boolean reserve, int count)
{
//class constant
//class variables
/*****************************************************/
room [count].updateReserve(reserve);
} // end
From the room class.
public void updateReserve(boolean newReserve)
{
//class constant
//class variables
/*****************************************************/
if (newReserve == false)
{
roomAvail = true;
}
else
{
roomAvail = false;
}
} // END
Well, there is some information missing in your question, however it think you are looking for:
public void updateReserve(boolean newReserve) {
if(newReserve && !roomAvail) {
System.out.println("Sorry this room is taken")
} else {
roomAvail = !newReserve;
}
}
With whatever i could understand about your question this is what i came up with -
public class Reservation {
public static void main(String args[]) {
Building building = new Building(20);
boolean reserve= false;
System.out.println("Which room would you like to reserve?");
System.out.println(building);
System.out.println("reserve: ");
int reservNum = 2;
building.reserveRoom(reserve, reservNum);
System.out.println("Is Reserved?:"+building.getRoom(reservNum).getRoomAvail());
}
}
class Building {
Room room[];
public Building(int numOfRooms) {
room = new Room[numOfRooms];
for(int i=0; i<numOfRooms; i++) {
room[i] = new Room();
}
}
public String toString() {
return "This Building has "+room.length+"rooms";
}
public Room getRoom(int roomNum){
return room[roomNum];
}
public void reserveRoom (boolean reserve, int count)
{
//class constant
//class variables
/*****************************************************/
room [count].updateReserve(reserve);
} // end
}
class Room {
boolean roomAvail;
public boolean getRoomAvail() {
return roomAvail;
}
public void updateReserve(boolean newReserve)
{
//class constant
//class variables
/*****************************************************/
if (newReserve == false)
{
roomAvail = true;
}
else
{
roomAvail = false;
}
} // END
}
How is it possible to set an object and method in a condition? I understand that, if the animal is over 50kg it weighs too much. But how about if an animal is hangry, need Love and feel boring return the method feelingNegative()?
I don't know how to set it. But after an animal sleeps, it is hangry. A thought would be:
Animal {
if (hangry == false && needLove == false && boring == false) {
return feelingNegative();
}
}
still don't know how to set it.
public class Animal {
private boolean needLove;
private boolean hangry;
private boolean boring;
private int kg;
public boolean sleep() {
return hangry = true;
}
public boolean watchTv() {
return needLove = true;
}
public void feelingPositive() {
System.out.println("I feel good");
}
public void feelingNeutral() {
System.out.println("Someting is missing...");
}
public void feelingNegative() {
System.out.println("I need love, food and fun!");
}
public void weight(int kg) {
if(50 < kg) {
System.out.println("You ate way too much");
}else {
System.out.println("You need to eat more");
}
}
}
The methods you are calling don't return anything (they are void). Just remove the return. And use boolean negation (!) instead of == false. Like,
if (!hangry && !needLove && !boring) {
feelingNegative();
}
The Method feelingNegative() doesn't return anything (Void). So you just have to define a method that call feelingNegative() when all the conditions are satisfied.
public void myMethod ()
{
if(!hangry && !needLove && !boring)
feelingNegative();
}
Could anyone tell me what purpose a return statement in a Finite State Machine's state serves? For example I have this code for a soccer player's state:
public class ChaseBall extends State<FieldPlayer> {
private static ChaseBall instance = new ChaseBall();
private ChaseBall() {
}
//this is a singleton
public static ChaseBall Instance() {
return instance;
}
#Override
public void Enter(FieldPlayer player) {
player.Steering().SeekOn();
}
}
#Override
public void Execute(FieldPlayer player) {
//if the ball is within kicking range the player changes state to KickBall.
if (player.BallWithinKickingRange() && player.isReadyForNextKick()) {
player.GetFSM().ChangeState(KickBall.Instance());
return;
}
//if the player is the closest player to the ball then he should keep
//chasing it
if (player.isClosestTeamMemberToBall()) {
player.Steering().SetTarget(player.Ball().Pos());
return;
}
//if the player is not closest to the ball anymore, he should return back
//to his home region and wait for another opportunity
player.GetFSM().ChangeState(ReturnToHomeRegion.Instance());
}
#Override
public void Exit(FieldPlayer player) {
player.Steering().SeekOff();
}
}
I was wondering if someone could explain what purpose the the return keywords in the first two if statements of the Execute() method serve?
Thanks
In this case it's mainly a formatting alternative to a series of else if clauses. It is logically equivalent to
if (<condition>) {
<code>
} else if (<condition>) {
<code>
} else {
<code>
}