Need mutator methods how do I do them - java

I am doing a UML and I am not quite sure how to do these mutator methods I am supposed to do this:
+turnOn(): void //sets on to true
+turnOff(): void //sets on to false
+channelUp(): void //increases channel by 1 if on, rolls to 1 after maximum
+channelDown(): void //decreases channel by 1 if on, rolls to maximum after 1
+volumeUp(): void //increases the volume by 1 if on and less than maximum
+volumeDown(): void //decreases volume by 1 if on and greater than 0
+toString( ): String //returns the current state(instance variable values)
my code right now: (keep in mind the mutator part isn't right)
public class TV {
private int volume;
private int channel;
private boolean on;
private int maxVolume;
private int maxChannel;
TV() {
volume = 1;
channel = 1;
on = false;
maxVolume = 1;
maxChannel = 1;
}
public int getChannel() {
return channel;
}
public int getVolume() {
return volume;
}
public boolean isOn() {
return on;
}
public int getMaxChannel() {
return maxChannel;
}
public int getMaxVolume() {
return maxVolume;
}
public void setChannel(int i) {
if (isOn() && i >= 1 && i <= maxChannel) channel = i;
}
public void setVolume(int i) {
if (isOn() && i >= 0 && i <= maxVolume) volume = i;
}
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setMaxVolume(int i) {
maxVolume = i;
}
// + turnOn() * * This is where the mutator methods begin I need help here * *
// if (channel == maxChannel) channel = 1;
// else channel++;
//if (channel == 1) channel = max;
//else channel--;
// if (volume == maxVolume) volume = 1;
// else channel++;
//if (volume == 1) volume = max;
// else channel--;
public string toString() {
return "channel: " + channel + "\nvolume: " + volume +
"\non: " + on + "\nmax Channel: " + maxChannel +
"\nmax Volume: " + maxVolume;
}
}

Mutator generally means the same things as 'setter'
So in your above code, a 'getter' would be:
public int getMaxChannel() {
return maxChannel;
}
and a 'mutator' or 'setter' would be:
public void setMaxChannel(int maxChannel) {
this.maxChannel = maxChannel;
}

Sample methods:
public void turnOn() {
this.on = true;
}
public void channelUp() {
if (on) {
if (channel == maxChannel) {
channel = 1;
}
else {
channel++;
}
}
}
public void volumeDown() {
if (on && volume > 0) {
volume--;
}
}
Other methods follows the same logic.
Strings in java are objects, so your toString method signature should read public String toString().

We use setters and mutator as interchangeably.
A mutator method is used to set a value of a private field. It follows
a naming scheme prefixing the word "set" to the start of the method
name. These methods do not have a return type and accept a parameter
that is the same data type as their corresponding private field. The
parameter is then used to set the value of that private field.
Below are some examples of mutators or setters:
public void setMaxChannel(int i) {
maxChannel = i;
}
public void setChannel(int c) {
channel=c;
}

Related

How to merge two alike items within the ArrayList?

So, I have 1 superclass DessertItem. Which has 4 subclasses Candy, Cookie, Ice Cream, Sundae. The Sundae class extends the Ice Cream class. Superclass is an abstract class. I also have a separate class which does not belong to the superclass, but in the same package - Order. There is another class - DessertShop, where the main is located.
Candy, Cookie classes implement SameItem<> generic class. The generic interface SameItem<> class looks like this:
public interface SameItem<T> {
public boolean isSameAs(T other);
}
The Candy, Cookie classes have this method:
#Override
public boolean isSameAs(Candy other) {
if(this.getName() == other.getName() && this.getPricePerPound() == other.getPricePerPound()) {
return true;
}
else {
return false;
}
}
And something similar, but for the cookie class.
All the subclasses have these methods :
default constructor,
public Cookie(String n, int q, double p) {
super(n);
super.setPackaging("Box");
cookieQty = q;
pricePerDozen = p;
}
public int getCookieQty() {
return cookieQty;
}
public double getPricePerDozen() {
return pricePerDozen;
}
public void setCookieQty(int q) {
cookieQty = q;
}
public void setToppingPricePricePerDozen(double p) {
pricePerDozen = p;
}
#Override
public double calculateCost() {
double cookieCost = cookieQty * (pricePerDozen/12);
return cookieCost;
}
and toString() method
So, what my program does is gets the input from the User, asks the name of the dessert, asks the quantity, or the quantity according to the dessert, ask the unit price. Asks the payment method. And then prints the receipt. This how the Order class looks like:
import java.util.ArrayList;
import java.util.List;
public class Order extends implements Payable{
//attributes
PayType payMethod;
private ArrayList<DessertItem> OrderArray;
//Constructor
public Order() {
OrderArray = new ArrayList<>();
payMethod = PayType.CASH;
}
//methods
public ArrayList<DessertItem> getOrderList(){
return OrderArray;
}// end of getOrderList
public ArrayList<DessertItem> Add(DessertItem addDesert){
enter code here
OrderArray.add(addDesert);
/* for(DessertItem i : getOrderList()) {
if(i instanceof Candy) {
for(DessertItem j : getOrderList()) {
if(j instanceof Candy) {
if(((Candy) i).isSameAs((Candy) j)) {
*/
//this is what I have tried so far, but I am lost
}
}
}
} else if(i instanceof Cookie) {
for (DessertItem j : getOrderList()) {
if(((Cookie) i).isSameAs((Cookie)j)) {
OrderArray.add(j);
} else {
OrderArray.add(i);
}
}
}
}
return OrderArray;
}// end of Add
public int itemCount(){
int counted = OrderArray.size();
return counted;
}//end of itemCount
public double orderCost() {
double orderResult = 0;
for(int i=0; i<OrderArray.size(); i++) {
orderResult = orderResult + OrderArray.get(i).calculateCost();
}
return orderResult;
}
public double orderTax() {
double taxResult = 0;
for(int i = 0; i<OrderArray.size(); i++) {
taxResult = taxResult + OrderArray.get(i).calculateTax();
}
return taxResult;
}
public double orderTotal() {
double ordertotal = orderTax() + orderCost();
return ordertotal;
}
#Override
public PayType getType() {
// TODO Auto-generated method stub
return payMethod;
}
#Override
public void setPayType(PayType p) {
payMethod = p;
}
public String toString() {
String finalOutput = "";
finalOutput += "------------------------Receipt--------------------------\n";
for(int i = 0; i < OrderArray.size(); i++) {
finalOutput = finalOutput + OrderArray.get(i).toString();
}
finalOutput += "--------------------------------------------------\n";
String line2 = "Total Number of items in order: " + itemCount() + "\n";
String line3 = String.format("Order Subtotals:\t\t\t\t $%-6.2f", orderCost());
String line4 = String.format("[Tax: $%.2f]\n", orderTax());
String line5 = String.format("\nOrder Total:\t\t\t\t\t $%-6.2f\n", orderTotal());
String outputVar = String.format("%s\n%s%s%17s", line2, line3, line4, line5);
String ending = "----------------------------------------------------";
String payType = String.format("\nPaid for with: %s", payMethod.name());
return finalOutput + outputVar + ending + payType;
}
So, my question is, how can I combine like items into one item?

Im trying to run BFS Algo and it throws me out

I`m trying to run BFS, when i get to PriorityQueue openList.add(state)
the first time it works and the secound time it dosent.
The error is:
Exception in thread "main" java.lang.ClassCastException: algorithms.mazeGenerators.Position cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at java.util.PriorityQueue.add(Unknown Source)
at algorithms.searchers.BFS.search(BFS.java:30)
at boot.Run.main(Run.java:18)
BFS CLASS:
public class BFS extends CommonSearcher {
#Override
public Solution search(Searchable s) {
State cur = null;
s.getStartState().setCost(0);
openList.add(s.getStartState());
HashSet<State> closedSet = new HashSet<State>();
while (!openList.isEmpty()) {
cur = popOpenList();
closedSet.add(cur);
if (cur.equals(s.getGoalState())) {
return backTrace(cur, s.getStartState());
}
ArrayList<State> successors = s.getAllPossibleStates(cur);
for (State state : successors) {
if (!closedSet.contains(state) && !openList.contains(state)) {
state.setCameFrom(cur);
state.setCost(cur.getCost() + 1);
openList.add(state);
} else {
if (openList.contains(state)) {
if (state.getCost() < returnWantedState(state).getCost()) {
openList.remove(state);
openList.add(state);
adjustPriorityList();
}
} else {
openList.add(state);
adjustPriorityList();
}
}
}
}
return null;
}
/*
* public State popOpenList() { State temp = openList.remove(); for (State
* state : openList) { if (temp.getCost() > state.getCost()) {
* openList.add(temp); temp = state; openList.remove(state); } } return
* temp;
*
* }
*/
public void adjustPriorityList() {
State temp = openList.remove();
for (State state : openList) {
if (temp.getCost() < state.getCost()) {
openList.add(temp);
temp = state;
openList.remove(state);
}
}
openList.add(temp);
}
public State returnWantedState(State state) {
for (State state1 : openList) {
if (state.equals(state1))
state = state1;
}
return state;
}
}
CommonSearcher Class:
package algorithms.searchers;
import java.util.PriorityQueue;
import algorithms.mazeGenerators.Searchable;
import algorithms.mazeGenerators.Solution;
import algorithms.mazeGenerators.State;
public abstract class CommonSearcher implements Searcher {
protected PriorityQueue<State> openList;
private int evaluatedNodes;
public CommonSearcher() {
openList = new PriorityQueue<State>();
evaluatedNodes = 0;
}
protected State popOpenList(){
evaluatedNodes++;
return openList.poll();
}
#Override
public abstract Solution search(Searchable s);
#Override
public int getNumberOfnodesEvaluated() {
// TODO Auto-generated method stub
return evaluatedNodes;
}
protected Solution backTrace(State goalState, State startState){
Solution sol = new Solution();
while(!goalState.equals(startState)){
sol.getSolutionList().add(goalState.getState());
goalState = goalState.getCameFrom();
}
return sol;
}
}
State Class:
package algorithms.mazeGenerators;
public abstract class State {
protected String state; // the state represented by a string
protected double cost; // cost to reach this state
protected State cameFrom; // the state we came from to this state
public State(){
}
public State(String state){ // CTOR
this.state = state;
}
#Override
public boolean equals(Object obj){ // we override Object's equals method
return state.equals(((State)obj).state);
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public State getCameFrom() {
return cameFrom;
}
public void setCameFrom(State cameFrom) {
this.cameFrom = cameFrom;
}
}
Position Class:
package algorithms.mazeGenerators;
import java.util.ArrayList;
public class Position extends State {
// Data members
private int x, y, z;
private int wallOrNot;
private boolean visted;
// Constructor
public Position() {
visted = false;
wallOrNot = 1;
}
/*
* The method gets the position details
* and checks if its a wall or not
* if its a wall then its marked as visited.
* */
public void setPos(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
if (z % 2 != 0 || x % 2 != 0 || y % 2 != 0)
visted = true;
setState("{" + x+"," + y+","+ z +"}");
}
// getrs and setters
public int getWallOrNot() {
return wallOrNot;
}
public void setWallOrNot(int wallOrNot) {
this.wallOrNot = wallOrNot;
}
public boolean isVisted() {
return visted;
}
public void setVisted(boolean visted) {
this.visted = visted;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getZ() {
return z;
}
public void setZ(int z) {
this.z = z;
}
/*
* This method gets returns all a list of neighbors that hasn't marked as visited for a specific Position.
* returns the list of neighbors.
* */
public ArrayList<Position> getNeighbors(Position[][][] maze) {
ArrayList<Position> neighbors = new ArrayList<Position>();
if (this.x > 1)
if (maze[x - 2][y][z].isVisted() == false)
neighbors.add(maze[x - 2][y][z]);
if (this.x < maze.length - 2)
if (maze[x + 2][y][z].isVisted() == false)
neighbors.add(maze[x + 2][y][z]);
if (this.y > 1)
if (maze[x][y - 2][z].isVisted() == false)
neighbors.add(maze[x][y - 2][z]);
if (this.y < maze[x].length - 2)
if (maze[x][y + 2][z].isVisted() == false)
neighbors.add(maze[x][y + 2][z]);
if (this.z > 1)
if (maze[x][y][z - 2].isVisted() == false)
neighbors.add(maze[x][y][z - 2]);
if (this.z < maze[x][y].length - 2)
if (maze[x][y][z + 2].isVisted() == false)
neighbors.add(maze[x][y][z + 2]);
return neighbors;
}
public String toString(){
return "{" + x+"," + y+","+ z +"}";
}
public boolean equals(Object obj){ // we override Object's equals method
return state.equals(((Position)obj).state);
}
}
The purpose of a priority queue requires an ordering of its elements.
In Java's PriorityQueue this can be done by either making the elements implement the Comparable interface,
or by specifying a Comparator.
I`m trying to run BFS, when i get to PriorityQueue openList.add(state) the first time it works and the secound time it dosent.
If you insert only one object into a PriorityQueue,
it will work even if the object doesn't implement the Comparable interface,
because a single object doesn't need to be compared to anything.
You get a ClassCastException when you insert a second object,
if the objects don't implement Comparable and you didn't provide a Comparator.
public abstract class State implements Comparable<State> {
// ...
#Override
public int compareTo(State other) {
if (getCost() > other.getCost()) {
return -1;
}
if (getCost() < other.getCost()) {
return 1;
}
return 0;
}
}
PriorityQueue requires its element to implement the Comparable interface, yet your State class does not do it.
From the java docs:
A priority queue relying on natural ordering also does not permit
insertion of non-comparable objects (doing so may result in
ClassCastException).
You need to make your State class something like:
public abstract class State implements Comparable<State> {
....
#Override
public int compareTo(State s) {
...
}
}

Confusion on using instanceof along with other inherited data

I have already made a posting about this program once, but I am once again stuck on a new concept that I am learning (Also as a side note; I am a CS student so please DO NOT simply hand me a solution, for my University has strict code copying rules, thank you.). There are a couple of difficulties I am having with this concept, the main one being that I am having a hard time implementing it to my purposes, despite the textbook examples making perfect sense. So just a quick explanation of what I'm doing:
I have an entity class that takes a Scanner from a driver. My other class then hands off the scanner to a superclass and its two subclasses then inherit that scanner. Each class has different data from the .txt the Scanner read through. Then those three classes send off their data to the entity to do final calculations. And that is where my problem lies, after all the data has been read. I have a method that displays a new output along with a few methods that add data from the super along with its derived classes.EDIT: I simply cannot figure out how to call the instance variable of my subclasses through the super so I can add and calculate the data.
Here are my four classes in the order; Driver, Entity, Super, Subs:
public static final String INPUT_FILE = "baseballTeam.txt";
public static void main(String[] args) {
BaseballTeam team = new BaseballTeam();
Scanner inFile = null;
try {
inFile = new Scanner(new File(INPUT_FILE));
team.loadTeam(inFile);
team.outputTeam();
} catch (FileNotFoundException e) {
System.out.println("File " + INPUT_FILE + " Not Found.");
System.exit(1);
}
}
}
public class BaseballTeam {
private String name;
private Player[] roster = new Player[25];
Player pitcher = new Pitcher();
Player batter = new Batter();
BaseballTeam() {
name = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public void loadTeam(Scanner input) {
name = input.nextLine();
for (int i = 0; i < roster.length; i++) {
if (i <= 9) {
roster[i] = new Pitcher();
}
else if ((i > 9) && (i <= 19)) {
roster[i] = new Batter();
}
else if (i > 19) {
roster[i] = new Player();
}
roster[i].loadData(input);
roster[i].generateDisplayString();
//System.out.println(roster[i].generateDisplayString()); //used sout to test for correct data
}
}
public void outputTeam() {
if ((pitcher instanceof Player) && (batter instanceof Player)) {
for (int i = 0; i < roster.length; i++) {
System.out.println(roster[i].generateDisplayString());
}
}
//How do I go about doing calculates?
public int calculateTeamWins() {
if ((pitcher instanceof ) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamSaves() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamERA() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamWHIP() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public double calculateTeamBattingAverage() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamHomeRuns() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateTeamRBI() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
public int calculateStolenBases() {
if ((pitcher instanceof Pitcher) && (batter instanceof Batter)) {
}
return 0;
}
}
public class Player {
protected String name;
protected String position;
Player(){
name = "";
position = "";
}
public String getName() {
return name;
}
public void setName(String aName) {
name = aName;
}
public String getPosition() {
return position;
}
public void setPosition(String aPosition) {
position = aPosition;
}
public void loadData(Scanner input){
do {
name = input.nextLine();
} while (name.equals(""));
position = input.next();
//System.out.println(generateDisplayString());
}
public String generateDisplayString(){
return "Name: " + name + ", Position:" + position;
}
}
public class Pitcher extends Player {
private int wins;
private int saves;
private int inningsPitched;
private int earnedRuns;
private int hits;
private int walks;
private double ERA;
private double WHIP;
Pitcher() {
super();
wins = 0;
saves = 0;
inningsPitched = 0;
earnedRuns = 0;
hits = 0;
walks = 0;
}
public int getWins() {
return wins;
}
public void setWins(int aWins) {
wins = aWins;
}
public int getSaves() {
return saves;
}
public void setSaves(int aSaves) {
saves = aSaves;
}
public int getInningsPitched() {
return inningsPitched;
}
public void setInningsPitched(int aInningsPitched) {
inningsPitched = aInningsPitched;
}
public int getEarnedRuns() {
return earnedRuns;
}
public void setEarnedRuns(int aEarnedRuns) {
earnedRuns = aEarnedRuns;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getWalks() {
return walks;
}
public void setWalks(int aWalks) {
walks = aWalks;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
wins = input.nextInt();
saves = input.nextInt();
inningsPitched = input.nextInt();
earnedRuns = input.nextInt();
hits = input.nextInt();
walks = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateERA();
calculateWHIP();
return String.format(super.generateDisplayString() + ", Wins:%1d, Saves:%1d,"
+ " ERA:%1.2f, WHIP:%1.3f ", wins, saves, ERA, WHIP);
}
public double calculateERA() {
try {
ERA = ((double)(earnedRuns * 9) / inningsPitched);
} catch (ArithmeticException e) {
ERA = 0;
}
return ERA;
}
public double calculateWHIP() {
try {
WHIP = ((double)(walks + hits) / inningsPitched);
} catch (ArithmeticException e) {
WHIP = 0;
}
return WHIP;
}
}
public class Batter extends Player {
private int atBats;
private int hits;
private int homeRuns;
private int rbi;
private int stolenBases;
private double batAvg;
Batter() {
super();
atBats = 0;
hits = 0;
homeRuns = 0;
rbi = 0;
stolenBases = 0;
}
public int getAtBats() {
return atBats;
}
public void setAtBats(int aAtBats) {
atBats = aAtBats;
}
public int getHits() {
return hits;
}
public void setHits(int aHits) {
hits = aHits;
}
public int getHomeRuns() {
return homeRuns;
}
public void setHomeRuns(int aHomeRuns) {
homeRuns = aHomeRuns;
}
public int getRbi() {
return rbi;
}
public void setRbi(int aRbi) {
rbi = aRbi;
}
public int getStolenBases() {
return stolenBases;
}
public void setStolenBases(int aStolenBases) {
stolenBases = aStolenBases;
}
#Override
public void loadData(Scanner input) {
super.loadData(input);
atBats = input.nextInt();
hits = input.nextInt();
homeRuns = input.nextInt();
rbi = input.nextInt();
stolenBases = input.nextInt();
}
#Override
public String generateDisplayString() {
calculateBattingAverage();
return String.format(super.generateDisplayString() +
", Batting Average:%1.3f, Home Runs:%1d, RBI:%1d, Stolen Bases:%1d"
, batAvg, homeRuns, rbi, stolenBases);
}
public double calculateBattingAverage() {
try{
batAvg = ((double)hits/atBats);
} catch (ArithmeticException e){
batAvg = 0;
}
return batAvg;
}
}
Also, its probably easy to tell I'm still fairly new here, because I just ran all my classes together in with the code sample and I can't figure out to add the gaps, so feel free to edit if need be.
The typical usage of instanceof in the type of scenario you're describing would be
if (foo instanceof FooSubclass) {
FooSubclass fooSub = (FooSubclass) foo;
//foo and fooSub now are references to the same object, and you can use fooSub to call methods on the subclass
} else if (foo instanceof OtherSubclass) {
OtherSubclass otherSub = (OtherSubclass) foo;
//you can now use otherSub to call subclass-specific methods on foo
}
This is called "casting" or "explicitly casting" foo to FooSubclass.
the concept to call the methods of your subclasses is called polymorphism.
In your runtime the most specific available method is called provided that the method names are the same.
so you can
Superclass class = new Subclass();
class.method();
and the method provided that overwrites the method in Superclass will be called, even if it's defined in the Subclass.
Sorry for my english, I hope that helps a little bit ;-)

The method is there but it does not work like it's supposed to

I have the following code -in Java btw- and it compiles fine but when I input invalid parameters it doesn't recognize them as errors and accepts them as if they met the conditions.The method that concerns me is SetMPG(int average) . It's my first time here so I apologize if my question is vague I would fill in more information if necessary.
public class Vehicle {
// instance variables - replace the example below with your own
private int tireCount;
private int mPG;
/**
* Constructor for objects of class Vehicle
*/
public Vehicle(int tCount, int mP) {
// initialise instance variables
tireCount = tCount;
mPG = mP;
}
public void setTire(int tire) {
if (tire >= 0) {
tireCount = tire;
} else/*if( tire < 0)*/ {
throw new IllegalArgumentException("Values must be positive");
}
}
public void setMPG(int average) {
if (average > 0) {
mPG = average;
} else if (average < 0) {
throw new IllegalArgumentException("Values must be positive");
}
}
public int getTire() {
return tireCount;
}
public int getMPG() {
return mPG;
}
public String toString() {
return String.format("There are " + tireCount + " tires and an average of " + mPG + "mpg");
}
public class VehicleTest
{
// instance variables - replace the example below with your own
public static void main(String []args)
{
Vehicle bike = new Vehicle( 2,-23); // first parameter is for tires , second is for MPG
System.out.println(bike);
}
}
Based on your code and what you're saying, It is most likely that you are setting your parameters via the constructor. Change your constructor to be of the form:
public Vehicle(int tCount , int mP)
{
// initialise instance variables
setTire(tCount);
setMPG(mP);
}
Also not sure whether 0 is a valid value for mpg???
public void setMPG(int average)
{
if( average > 0) //should it be >= 0???
{
mPG=average;
}
else if(average < 0) // should it be <=0 ????
{
throw new IllegalArgumentException("Values must be positive");
}
}

Exception in thread "main" java.lang.NullPointerException in a finished program [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I got to what I thought was a finished program and now java is pulling this on me.
The error I get is as follows:
Exception in thread "main" java.lang.NullPointerException
at hirecardemo.HireCar.isAvailable(HireCar.java:68)
at hirecardemo.HireCarDemo.runSimulation(HireCarDemo.java:49)
at hirecardemo.HireCarDemo.main(HireCarDemo.java:25)
Java Result: 1
Main Class:
package hirecardemo;
import java.util.Random;
public class HireCarDemo {
public static void main(String[] args) {
HireCar car0 = new HireCar("Toyota", "AV77 FGJ", 6000, 12300, 41500);
HireCar car1 = new HireCar("Mercedes", "DI99 FTZ", 6700, 7000, 91800);
HireCar car2 = new HireCar("Toyota", "FG82 FTP", 25000, 12000, 72000);
HireCar car3 = new HireCar("Vauxhall", "TW56 LTS", 10000, 11000, 19001);
HireCar car4 = new HireCar("Ford", "TD85 LTU", 13000, 12300, 12000);
HireCar car5 = new HireCar("Susuki", "GU12 UTJ", 12000, 10000, 50000);
HireCar[] fleet = {car0, car1, car2, car3, car4, car5};
int minMileage = 1000;
int maxMileage = 60000;
int numberOFevents = 12;
String [] results = HireCarDemo.runSimulation(fleet, numberOFevents,
minMileage, maxMileage);
for(int i = 0; i < numberOFevents; i++) {
System.out.println(results[i]);
}
}
/**
* #param fleet the fleet of hire cars
* #param numberOFevents the size of the events table to be generated
* #param minMileage the assumed minimum mileage driven by any hired
* car
* #param maxMileage the assumed maximum mileage driven by any hired
* car
* #return table of events generated during the simulation
*/
public static String[] runSimulation(HireCar [] fleet, int numberOFevents,
int minMileage, int maxMileage) {
int n = fleet.length; // Number of cars in the fleet.
Random carGenerator = new Random();
String [] events = new String [numberOFevents];
for(int i = 0; i < numberOFevents; i++) {
int randomNumber = carGenerator.nextInt(n-1);
if(fleet[randomNumber].isAvailable() == true)
{
fleet[randomNumber].hireOut();
events[i] = fleet[randomNumber].getRegNumber() + " <HIRE OUT>";
}
else if(fleet[randomNumber].isOnHire() == true)
{
Random mileage = new Random();
int randomMileage = mileage.nextInt(maxMileage - minMileage);
if(fleet[randomNumber].isBeingServiced() == true)
{
events[i] = fleet[randomNumber].getRegNumber() +
" <RETURN FROM HIRE>" + " <SEND FOR SERVICE>";
} else {
events[i] = fleet[randomNumber].getRegNumber() +
" <RETURN FROM HIRE>";
}
}
else
{
fleet[randomNumber].makeAvailable();
events[i] = fleet[randomNumber].getRegNumber() +
" <RETURN FROM SERVICE>";
}
}
return events;
}
}
Here is my separate class that goes along with this:
//******************************************************************************
// HireCar.java Author: Ryan Holder
//
// Represents the car hire company's fleet of cars and the information on them.
//******************************************************************************
package hirecardemo;
public class HireCar {
private String manufacturer, regNumber, carStatus;
private int mileage, serviceInterval, lastService; // All in miles.
private boolean serviceDue() {
if((mileage- lastService) >= serviceInterval) {
this.sendForService();
return true;
} else {
return false;
}
}
private void sendForService() {
carStatus = "Servicing";
}
//--------------------------------------------------------------------------
// Default Constructor: Sets information for a new car.
//--------------------------------------------------------------------------
public HireCar(String demoManufacturer, String demoRegNumber) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
carStatus = "Available";
serviceInterval = 0;
lastService = 0;
mileage = 0;
}
public HireCar(String demoManufacturer, String demoRegNumber,
int demoMileage, int demoServiceInterval, int lastInterval) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
mileage = demoMileage;
}
public void setMileage(int demoMileage) {
mileage = demoMileage;
}
public void setServiceInterval(int demoServiceInterval) {
serviceInterval = demoServiceInterval;
}
public void setLastService(int demoLastService) {
lastService = demoLastService;
}
public String getRegNumber() {
return regNumber;
}
public void makeAvailable() {
carStatus = "Available";
}
public boolean isAvailable() {
if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
return true;
} else {
return false;
}
}
public boolean isOnHire() {
if(carStatus.equals("On Hire")) {
return true;
} else {
return false;
}
}
public boolean isBeingServiced() {
if(carStatus.equals("Being Serviced")) {
return true;
} else {
return false;
}
}
public void hireOut() {
carStatus = "On Hire";
}
public void returnFromHire() {
if(this.serviceDue() == true) {
carStatus = "Being Serviced";
} else {
carStatus = "Available For Hire";
}
}
public void returnFromService() {
carStatus = "Return From Service";
}
public String ToString() {
return("Manufacturer: <" + this.manufacturer + ">/n "
+ "Registration Number: <" + this.regNumber + ">/n"
+ "Mileage: <" + this.mileage + ">/n"
+ "Service Interval: <" + this.serviceInterval + "</n"
+ "Last Service: <" + this.lastService + "</n"
+ "Status: <" + this.carStatus + "</n");
}
}
You are using 5-arg constructor to construct your HireCar instance: -
new HireCar("Toyota", "AV77 FGJ", 6000, 12300, 41500);
And in that constructor, you haven't set the value for - "carStatus".
public HireCar(String demoManufacturer, String demoRegNumber,
int demoMileage, int demoServiceInterval, int lastInterval) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
mileage = demoMileage;
}
So, carStatus is still null. (You should set every field in this constructor. At least the references, because their default value is null)
So, when you invoke the isAvailable method for any of the instance you added in your array: -
fleet[randomNumber].isAvailable()
It will result in a NPE, as in isAvailable method, you are invoking equals method on carStatus: -
if(carStatus.equals("Available") || carStatus.equals("Return from Service"))
^^^
This is null here
The stacktrace is telling you that the isAvailable method is throwing a NullPointerException, so let's look at that.
public boolean isAvailable() {
if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
return true;
} else {
return false;
}
}
Unnecessary return true/false aside, the only thing here that gets dereferenced is car status, so when can it be null?
Well, look at the constructor you're using: the one with 5 arguments. At no point does it ever set the status, so it remains null. Hence the null pointer.
Use an Enum in place of String for carStatus
Initialize all the attributes in ALL constructors (the second left carStatus = null)
you are initializing carStatus in a constructor with 2-args and you never invoke that constructor, thus, carStatus is still null when you call equals() in isAvailable() method.
     
  if(carStatus.equals("Available") || carStatus.equals("Return from Service")) {
^^^ This is **null** as it is not initialized yet, Thus **NPE**.
you should also intialize carStatus in your 5-args Constructor in-order for your current code to work.
public HireCar(String demoManufacturer, String demoRegNumber,
int demoMileage, int demoServiceInterval, int lastInterval) {
manufacturer = demoManufacturer;
regNumber = demoRegNumber;
mileage = demoMileage;
carStatus="someval" ; //initialize carStatus here
}

Categories

Resources