The requirements for this class is as follows:
Write a class called Elevator that should contain the following member variables:
currentFloor (int)
elevatorState (an int constant, either IDLE, TO_SOURCE, or TO_DESTINATION)
request (Request object representing the request being handled or null if the Elevator is idle)
You should also provide for this class the following:
A default constructor that sets request to null, elevatorState to IDLE, and currentFloor to 1.
Accessor and mutator methods for each variable.
Final variables to represent IDLE, TO_SOURCE, and TO_DESTINATION.
Heres what I have:
public class Elevator {
private int currentFloor;
private int elevatorState;
private Elevator request;
public Elevator(){
currentFloor = 1;
elevatorState = ; //this is my problem
request = null;
}
}
Im confused because it says to declare IDLE, TO_Source, and TO_DESTINATION as integer constants but wouldn't they be strings?
Any clarification would be very helpful.
Basically, what is being asked of is 3 int constants:
public static final int IDLE = 0;
public static final int TO_SOURCE = 1;
public static final int TO_DESTINATION = 2;
public Elevator(){
currentFloor = 1;
elevatorState = IDLE; //this is no longer my problem
request = null;
}
However, if you want to be a mister fancy pants and use OOP properly (something that may not be taught), you could use an Enum!
public enum ElevatorState {
IDLE, TO_SOURCE, TO_DESTINATION
}
Then in your class:
public class Elevator {
private ElevatorState elevatorState;
private int currentFloor;
private Elevator request;
public Elevator() {
currentFloor = 1;
elevatorState = ElevatorState.IDLE; //this is no longer my problem
request = null;
}
}
My Java is a little rusty, but this should be okay to use.
Well here is a possible solution to the problem:
public class Elevator
{
private static final int IDLE = 0;
private static final int TO_SOURCE = 1;
private static final int TO_DESTINATION = 2;
private int currentFloor;
private int elevatorState;
private Elevator request;
public Elevator(){
currentFloor = 1;
elevatorState = IDLE; //this is my problem
request = null;
}
public int getCurrentFloor() {
return currentFloor;
}
public void setCurrentFloor(int currentFloor) {
this.currentFloor = currentFloor;
}
public int getElevatorState() {
return elevatorState;
}
public void setElevatorState(int elevatorState) {
if( elevatorState == IDLE ) setRequest( null );
this.elevatorState = elevatorState;
}
public Elevator getRequest() {
return request;
}
public void setRequest(Elevator request) {
this.request = request;
}
}
Related
I'm positive I covered the basics. I put #Override before overriding methods. I made sure to include 'extends Super' on the line of the class. I can't override the constructor either. I passed the right amount of variables of the correct type and it gives me an error message saying 'actual and formal argument lists differ in length.' Along with errors not reading the static variables from the TuitionConstants class.
// This is the super class
public abstract class Student implements Comparable<Student> {
private int mCredits;
private String mFirstName;
private String mId;
private String mLastName;
private double mTuition;
public Student(String pId, String pFirstName, String pLastName) {
mId = pId;
mFirstName = pFirstName;
mLastName = pLastName;
}
public abstract void calcTuition();
#Override
public int compareTo(Student pStudent) {
return getId().compareTo(pStudent.getId());
}
public int getCredits() {
return mCredits;
}
public String getFirstName() {
return mFirstName;
}
public String getId() {
return mId;
}
public String getLastName() {
return mLastName;
}
public double getTuition() {
return mTuition;
}
public void setCredits(int pCredits) {
mCredits = pCredits;
}
public void setFirstName(String pFirstName) {
mFirstName = pFirstName;
}
public void setId(String pId) {
mId = pId;
}
public void setlastName(String pLastName) {
mLastName = pLastName;
}
protected void setTuition(double pTuition) {
mTuition = pTuition;
}
}
import p02.Student;
import p02.TuitionConstants;
public class OnCampusStudent extends Student {
public static final int RESIDENT = 1;
public static final int NON_RESIDENT = 2;
private int mResident;
private double mProgramFee;
//Error on this constructor. Says 'actual and formal argument lists differ in length
public OnCampusStudent(String pId, String pFirstName, String pLastName) {
super(pId, pFirstName, pLastName);
}
// Errors on this method. On #Override line:"method does not override or implement a method
// from a supertype. Also on the lines that call getCredits(), it says "cannot find symbol,"
// but it's a method from the superclass. Same "cannot find symbol" error on the lines that call
// the static variables from the TuitionConstants class.
#Override
public void calcTuition() {
double t;
if (getResidency() == RESIDENT) {
t = TuitionConstants.ONCAMP_RES_BASE;
} else {
t = TuitionConstants.ONCAMP_NONRES_BASE;
}
t = t + getProgramFee();
if (getCredits() > TuitionConstants.ONCAMP_MAX_CREDITS) {
t = t + (getCredits() - TuitionConstants.ONCAMP.MAX.CREDITS) * TuitionConstants.ONCAMP_ADD_CREDITS;
}
setTuition(t);
}
}
// Here is the TuitionConstants Class.
public class TuitionConstants {
public static final int ONCAMP_ADD_CREDITS = 475;
public static final int ONCAMP_MAX_CREDITS = 18;
public static final int ONCAMP_NONRES_BASE = 14875;
public static final int ONCAMP_RES_BASE = 7575;
public static final int ONLINE_CREDIT_RATE = 950;
public static final int ONLINE_TECH_FEE = 75;
}
public class GPSping {
private double pingLat;
private double pingLon;
private int pingTime;
}
The Trip class
public class Trip {
private ArrayList<GPSping> pingList;
public Trip() {
pingList = new ArrayList<>();
}
public Trip(ArrayList<GPSping> triplist) {
pingList = new ArrayList<>();
}
public ArrayList<GPSping> getPingList() {
return this.pingList;
}
public boolean addPing(GPSping p) {
int length = pingList.size();
int Time = pingList.get(length);
if (p.getTime() > this.pingList[length]) {
pinglist.add(p);
return True;
} else {
return False;
}
}
}
I am trying to add a GPS ping to this trip list but only if the time of p is after the last time in this trip list. I am very new to Java and am struggling with wrapping my head around the syntax some help would be greatly appreciated.
First element in List has index 0, to to get the last one:
int Time = pingList.get(length - 1);
But I think, it's better to store maxPingTime to check it before add new GPSping:
class Trip {
private final List<GPSping> pingList = new ArrayList<>();
private int maxPingTime = Integer.MIN_VALUE;
public List<GPSping> getPingList() {
return pingList.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(pingList);
}
public boolean addPing(GPSping p) {
if (p.getPingTime() <= maxPingTime)
return false;
pingList.add(p);
maxPingTime = p.getPingTime();
return true;
}
}
final class GPSping {
private final double pingLat;
private final double pingLon;
private final int pingTime;
public GPSping(double pingLat, double pingLon, int pingTime) {
this.pingLat = pingLat;
this.pingLon = pingLon;
this.pingTime = pingTime;
}
}
P.S. Pay attention on Encapsulation OOP principle: GPSping should be final and pingList should not be directly retrieved.
I don't get what's going on here, but the final method
s.castable()
that overrides the motherclass's namesake abstract method doesn't get called.
Here is where I try to call s.castable():
public void cast(String[] request) {
System.out.println("cast called");
if (this.session.getPlayer()==this.game.getTurnPlayer()) {
System.out.println("first condition passed");
Spell s = this.session.getPlayer().getCharacter().getSpells().get(Integer.valueOf(request[1]));
ArrayList<String> usernames = new ArrayList();
System.out.println("Now printing spell: "+s);
for (int i = 6; i < request.length; i++) {
usernames.add(request[i]);
}
System.out.println("username create.d");
if (s.castable()) { //HERE
System.out.println("Second condition passed");
s.cast(Integer.valueOf(request[1]), Integer.valueOf(request[2]),request[3].charAt(0), request[4].charAt(0), usernames);
String str = "";
for (String st : usernames) {
str += st;
}
this.session.send("YOUSPELL "+request[1]+" "+request[2]+" "+request[3]+" "+request[4]+" "+str);
System.out.println("Done");
}
}
}
Here is the "Spell" MotherClass:
public abstract class Spell {
private int manaCost;
private int coolDown;
private int range;
private Player player;
public abstract void cast(int x, int y, char mode1, char mode2,ArrayList<String> usernames);
public abstract Boolean castable();
//Then all getters and setters.
}
And here is the final class "Velocity":
public final class Velocity extends Spell {
private final int manaCost;
private final Player player;
private final int coolDown;
private final int coolDownTime;
private final int additionalMovement;
private final int spellRef;
private final ArrayList<String> usernames = new ArrayList();
public Velocity(Player p) {
this.spellRef = 0;
this.additionalMovement = 5;
this.player = p;
this.manaCost = 5;
this.coolDownTime = 3;
this.coolDown = 0;
super.setCoolDown(coolDown);
super.setManaCost(manaCost);
super.setPlayer(p);
}
#Override
public final void cast(int x, int y, char mode1, char mode2,ArrayList<String> usernames) {
System.out.println("Velocity casted.");
player.setMovement(player.getMovement() + additionalMovement);
setCoolDown(coolDownTime);
}
#Override
public final Boolean castable() {
System.out.println(player.getMana());
System.out.println(manaCost);
System.out.println(getCoolDown());
if (player.getMana() >= manaCost && getCoolDown() >= 0) {
return true;
}
return false;
}
}
Finally, the console output:
cast called
first condition passed
Now printing spell: model.haraka.be.Velocity#739bb60f
username create.d.
As you can see the spell object is known.
Can you help me ?
Thank you
The only possible problem here can be that Abstract class Spell's variable s doesn't contain the reference to Velocity object.
hence the castable method of velocity class never gets called.
If the castable method is returning false as mentioned by many
people System.out.println() statements must be printed which is not
the case I think.
But to be sure this is the problem, Please explain:
Spell s = this.session.getPlayer().getCharacter().getSpells().get(Integer.valueOf(request[1]));
What are below methods return type ?
getPlayer()
getSpells()
get(Integer.valueOf(request[1])
This is too much to ask/comment in comment section hence posting as an answer.
I have a class which only allows integers with limited amount. The problem is, class is doing its work but when I use multiple objects, it only takes the last objects limitation number and applies to others.
I also couldn't get rid of static warnings.
Code is ;
public class LimitedIntegerTF extends JTextField {
private static final long serialVersionUID = 1L;
private static int limitInt;
public LimitedIntegerTF() {
super();
}
public LimitedIntegerTF(int limitInt) {
super();
setLimit(limitInt);
}
#SuppressWarnings("static-access")
public final void setLimit(int newVal)
{
this.limitInt = newVal;
}
public final int getLimit()
{
return limitInt;
}
#Override
protected Document createDefaultModel() {
return new UpperCaseDocument();
}
#SuppressWarnings("serial")
static class UpperCaseDocument extends PlainDocument {
#Override
public void insertString(int offset, String strWT, AttributeSet a)
throws BadLocationException {
if(offset < limitInt){
if (strWT == null) {
return;
}
char[] chars = strWT.toCharArray();
boolean check = true;
for (int i = 0; i < chars.length; i++) {
try {
Integer.parseInt(String.valueOf(chars[i]));
} catch (NumberFormatException exc) {
check = false;
break;
}
}
if (check)
super.insertString(offset, new String(chars),a);
}
}
}
}
How I call it on another class ;
final LimitedIntegerTF no1 = new LimitedIntegerTF(5);
final LimitedIntegerTF no2 = new LimitedIntegerTF(7);
final LimitedIntegerTF no3 = new LimitedIntegerTF(10);
The result is no1, no2, and no3 has (10) as a limitation.
Example:
no1: 1234567890 should be max len 12345
no2: 1234567890 should be max len 1234567
no3: 1234567890 it's okay
It's because your limitInt is static, which means it has the same value for all instances of that class (What does the 'static' keyword do in a class?). Make it non-static, and each instance of your class will have their own value for it.
If you want to use limitInt in the inner class UpperCaseDocument, then make that class non-static as well. However, if you do that, each instance of UpperCaseDocument will also have an instance of LimitedIntegerTF associated with it.
It's a little bit difficult but i'll try to explain my problem. I've created a program with a superclass (RichIndustrialist) two subclasses (PredecessorRichIndustrialist and another one I didn't add) and 4 subclasses to these subclasses (CrazyRichIndustrialist and another 3). Now, the program is too difficult to explain but the problem is actually simple. My constructor is in the superclass and every subclass use it to initilize. Every time I create a new subclass object like CrazyRichIndustrialist, it resets all the already existed subclasses (from any subclass) to the value of the new object. I don't know how to fix this. Thank you in advance...
RichIndustrialist:
package Mortal;
import java.util.Random;
public class RichIndustrialist implements Mortal {
private static String Name;
private static double holdings;
private static int Alive;
public RichIndustrialist(String Rich_Name, double Rich_holdings) {
this.Name = Rich_Name;
this.holdings = Rich_holdings;
this.Alive = 1;
}
public int isAlive() {
return (this.Alive);
}
public void setHoldings(double new_holdings) {
this.holdings = new_holdings;
}
public double getHoldings() {
return (this.holdings);
}
public String getName() {
return (this.Name);
}
public void die() {
this.Alive = 0;
}
public void getHeritage(double heritage) {
this.holdings = this.holdings + heritage;
}
}
PredecessorRichIndustrialist:
package Mortal;
import java.util.Arrays;
public class PredecessorRichIndustrialist extends RichIndustrialist {
private static String Name;
private static double holdings;
private RichIndustrialist[] successors = {};
private static int Alive;
public PredecessorRichIndustrialist(String Rich_Name, double Rich_holdings) {
super(Rich_Name,Rich_holdings);
}
public void die() {
super.die();
}
public void Inheritance(double holdings, RichIndustrialist[] successors) {
int i = 0;
while (i < successors.length) {
int Alive = successors[i].isAlive();
System.out.println(Alive);
if (Alive == 0) {
removeSuccessor(successors[i]);
i++;
} else {
i++;
}
}
}
public void addSuccessor(RichIndustrialist new_successor) {
RichIndustrialist[] new_successors = new RichIndustrialist[successors.length + 1];
if (successors.length == 0) {
new_successors[0] = new_successor;
successors = new_successors;
} else {
for (int i = 0; i < successors.length; i++) {
new_successors[i] = successors[i];
}
new_successors[new_successors.length - 1] = new_successor;
}
this.successors = new_successors;
}
public void removeSuccessor(RichIndustrialist removed_successor) {
RichIndustrialist[] new_successors = new RichIndustrialist[this.successors.length - 1];
int j = 0;
for (int i = 0; i < this.successors.length; i++) {
if (!this.successors[i].equals(removed_successor)) {
new_successors[j] = this.successors[i];
} else {
j--;
}
j++;
}
}
public RichIndustrialist[] getSuccessors() {
return successors;
}
}
CrazyRichIndustrialist:
package Mortal;
import java.util.Random;
public class CrazyRichIndustrialist extends PredecessorRichIndustrialist {
private RichIndustrialist[] successors = {};
private static String Name;
private static double holdings;
private static int Alive;
public CrazyRichIndustrialist(String Rich_Name, double Rich_holdings) {
super(Rich_Name,Rich_holdings);
}
public void die() {
super.die();
Inheritance(getHoldings(),getSuccessors());
}
public void addSuccessor(RichIndustrialist new_successor) {
super.addSuccessor(new_successor);
}
public void removeSuccessor(RichIndustrialist removed_successor) {
super.removeSuccessor(removed_successor);
}
public void Inheritance (double holdings , RichIndustrialist[] successors) {
super.Inheritance(holdings, successors);
for (int i=0; i<successors.length-1; i++)
{
double random = new Random().nextDouble();
double amount = this.holdings * random;
successors[i].getHeritage(amount);
holdings = this.holdings - amount;
}
successors[successors.length-1].getHeritage(this.holdings);
this.holdings = 0;
}
public String getName(){
return super.getName();
}
public double getHoldings(){
return super.getHoldings();
}
public RichIndustrialist[] getSuccessors(){
return super.getSuccessors();
}
public void setHoldings(double new_holdings){
super.setHoldings(new_holdings);
}
public int isAlive() {
return super.isAlive();
}
public void getHeritage(double heritage) {
super.getHeritage(heritage);
}
}
Most of your fields are static. What that means is that all the instances of your classes share the same value. When you call the constructor, the static fields are modified, which affects all the existing instances.
For example:
this.Name = Rich_Name;
should actually have been written:
RichIndustrialist.Name = Rich_Name;
You can read about the difference between instance and class (or static) members in this tutorial.
The following fields should be declared as non-static. When these fields are declared as static each RichIndustrialist instance will share these fields and their assigned values. Declaring them as non-static allows each RichIndustrialist instance to have its own copy of these fields, which is autonomous from the other instances of RichIndustrialist.
private String Name;
private double holdings;
private int Alive;
Here is a good description of static from the Java Tutorial
Sometimes, you want to have variables that are common to all objects.
This is accomplished with the static modifier. Fields that have the
static modifier in their declaration are called static fields or class
variables. They are associated with the class, rather than with any
object. Every instance of the class shares a class variable, which is
in one fixed location in memory. Any object can change the value of a
class variable, but class variables can also be manipulated without
creating an instance of the class.
Your properties/variables are static. and we know static variable are shared between all the objects.
That is the reason the last object will replace the existing value of your variables
Suggestion:
change your static modifier to instance modifier
From
private static String Name;
private static double holdings;
private static int Alive;
To
private String Name;
private double holdings;
private int Alive;
I am sure your problem will resolve.
You are declaring the Name member field in all of your classes, you should only declare it in the super-class and let the other sub-classes (re)use it.
Furthermore, you declared the field as static, all instances of your class will use the same field, which is probably not what you intended, so remove the static part.
Same goes for all of your other member fields.
Note: do not start the member fields with a capital: Name should be defined and used as name. Class names on the other hand should start with a capital! This is a generically accepted Java convention and keeps things more clear/separated.