The two methods need to consider the boolean onLoan from the a second class named car for them to be able to be applied, what I mean is that only cars which onLoan == false should be considered. I got to the base of them tried what it came to my mind about getting this solved but nothing for me seems to work at the moment some suggestions? Thank you!
/**
* Constructor for objects of class RentalCompany
*/
public void showAllCarsNotOnloan ()
{
for ( Car car:cars) {
if (cars.size()>0 ) {
int i = 0;
System.out.println(car.getDescription());
i++;
}
else if ( cars.size() < 0 ){
System.out.println ("Add cars first");
}
}
}
and the second method
public Car searchCar(String description)
{
for (Car car : cars) {
if (car.getDescription() == description) {
return car;
}
else {
System.out.println("This car is not listed. Retry!!");
}
}
return null;
}
The following will do the work:
The Car class:
public class Car {
private boolean onLoan;
// Other variables...
public boolean isOnLoan() {
return onLoan;
}
// Other methods....
}
Now, the showAllCarsNotOnloan method
public void showAllCarsNotOnloan() {
if (cars.size() == 0) {
System.out.println("Add cars first!");
return;
}
for (Car car : cars) {
if (!car.isOnLoan()) {
System.out.println(car.getDescription());
}
}
}
and the searchCar method
public Car searchCar(String description) {
for (Car car : cars) {
if (car.getDescription().equals(description)) {
return car;
}
}
System.out.println("This car not listed. Retry!!");
return null;
}
Related
I am trying to write an ADT for a class that incorporates a sequence when there is a small amount of data to store (<1000 key values) and uses a HashTable otherwise. I have to write the sequence class myself but i was delighted to find out that java has it's own built in HashTable class. However, one of the requirements for this ADT is that it must be able to display the previous and next keys (called VINs in the code). I can do this easily with my sequence class, however I was wondering if the built in HashTable class had such a function. Will I have to write my own HashTable class or is there a way I can achieve my goal without having to do so? Thank you all for your help in advance, I really appreciate it!
This is the CVR class (data is passed to this class and it calls upon the sequence or HastTable class)
import java.util.*;
public class CVR
{
//this will be used to generate random alpha numeric numbers
private final static String alphaNumeric="ABDCEFGHIJKLMNOPQRSTUVWXYZ0123456789";
//key
private String VIN;
//threshold (determines which ADT to use)
private int threshold;
//length of key
private int VINLength;
//this is an object of Archive which will hold the data associated with VIN
private Account value;
//TBD
//private Collection<Account> activeVINS;
//HashMap to store all the key-value pairs
//the value come in the form of a stack because,
//multiple events can be associated with the same
//VIN, and must be shown in reverse-chronological order
private Hashtable<String, Stack<Account>> hashRecords;
private sequence seqRecords;
//This will keep track of all VINs and make sure
//none of them are repeated
private HashSet<String> VINRecorder;
private boolean hashTabl=false;
//default constructor
public CVR(int threshold) throws Exception
{
this.setThreshold(threshold);
if (threshold>1000)
{
hashRecords=new Hashtable<>();
hashTabl=true;
}
else
{
seqRecords=new sequence();
hashTabl=false;
}
}
//not sure this is even needed
//parameterized constructor for CVR, takes VIN
//and adds it to VINRecorder
//re-evaluate this method, with this a VIN is added to HashSet, but not to
//HashMap. At the same time I'm not sure We want VINs w/o associated accounts
//to be in HashMap. TBD
//For now actually, I will add them to HashMap, this may change down the line...
/**
public CVR (String VIN) throws Exception
{
this.VIN=VIN;
records=new Hashtable<>();
VINRecorder=new HashSet<>();
add(VIN, null);
//Stack<Account> stack = new Stack<Account>();
//VINRecorder.add(VIN);
}
**/
//accessors and mutators
//VIN getters and setters
public String getVIN()
{
return VIN;
}
public void setVIN(String VIN)
{
this.VIN=VIN;
VINRecorder=new HashSet<>();
VINRecorder.add(VIN);
}
//threshold getters and setters
public int getThreshold()
{
return threshold;
}
//for this one we have to keep in mind the restriction set
//on us in the instructions
public void setThreshold(int threshold) throws Exception
{
if(threshold<100 || threshold>900000)
{
//System.out.println("Invalid input for threshold");
throw new Exception("Invalid input for threshold");
}
else
{
this.threshold=threshold;
}
}
//VINLength getters and setters
public int getVINLength()
{
return VINLength;
}
//again for this one. we need to take the
//instructions into account for this special
//case
public void setVINLength(int VINLength) throws Exception
{
if(VINLength<10 || VINLength>17)
{
throw new Exception("Invalid input for VIN length");
}
else
{
this.VINLength=VINLength;
}
}
//Now onto the methods
//Generate method
//This method should randomly generate a sequence
//containing n new non-existing valid keys
//***Must determine whether the output is a sequence or not
public String generate(int size) throws Exception
{
char[] Arr= alphaNumeric.toCharArray();
String[] ender=new String[size];
//generating random number between 10 and 17
Random r= new Random();
int low=10;
int high=17;
for(int x=0; x<size;x++)
{
int highLow=r.nextInt(high-low)+10;
StringBuilder newString=new StringBuilder();
//making string between length of 10 and 17 randomly
for(int i=0; i<highLow; i++)
{
newString.append(Arr[new Random().nextInt(Arr.length)]);
}
///////////////////
String newVIN=newString.toString();
//System.out.println(newVIN);
//This must be further explored, I do not know why,
//but for some reason it does not work if the first
//condition is not there, to be explored
if(newVIN!=null)
{
}
//stops here for some reason, must find out why, something is wrong with this statement
else if(VINRecorder.contains(newVIN))
{
x--;
}
else
{
ender[x]=newString.toString();
}
ender[x]=newString.toString();
}
//System.out.println("hello");
System.out.println(Arrays.toString(ender));
return Arrays.toString(ender);
}
//method allKeys
//this method should return all keys as a sorted
//sequence in lexicographic order
//the plan here is to use
/**
public LinkedList<Account> allKeys()
{
}
**/
//add method
//****must check to see if must be resized later
public void add(String VIN, Account value) throws Exception
{
if(hashTabl==true)
{
if(!VIN.equals(value.getVIN()))
{
System.out.println("Something went wrong :/");
throw new Exception("VIN does not match account");
}
else if(hashRecords.containsKey(VIN))
{
System.out.println("VIN exists, adding to record");
hashRecords.get(VIN).add(value);
System.out.println("Success!");
}
else
{
System.out.println("New account made, record added!");
Stack<Account> stack = new Stack<Account>();
stack.add(value);
hashRecords.put(VIN, stack);
System.out.println("Success!");
//resize here
//
}
}
else
{
if(value==null)
{
Account saveVIN=new Account(VIN);
seqRecords.add(saveVIN);
}
seqRecords.add(value);
}
}
//remove method
//***must check to see if must be resized later
public void remove(String VIN)
{
if(hashTabl==true)
{
if(hashRecords.containsKey(VIN))
{
hashRecords.remove(VIN);
//resize here
//
}
else
{
System.out.println("Key does not exist in HashTable");
}
}
else
{
seqRecords.removeVIN(VIN);
}
}
//getValues method
public Stack<Account> getValues(String VIN)
{
if(hashTabl == true)
{
if(hashRecords.containsKey(VIN))
{
Stack<Account> values = new Stack<Account>();
values=hashRecords.get(VIN);
return values;
}
else
{
System.out.println("This VIN could not be found in directory");
return null;
}
}
else
{
return seqRecords.getAccount(VIN);
}
}
//nextKey methods
public String nextVIN(String VIN)
{
//unfinished, not sure what to call here
if(hashTabl=true)
{
return hashRecords.
}
else
{
return seqRecords.nextVIN(VIN);
}
}
//previous Accidents method
public Stack<Account> prevAccids(String VIN)
{
if(hashTabl == true)
{
if(hashRecords.contains(VIN))
{
Stack<String> Accids= new Stack<String>();
Stack<Account> temp; //= new Stack<Account>();
temp=hashRecords.get(VIN);
return temp;
/**
String tempString;
while(!temp.isEmpty())
{
tempString=temp.pop().getAccids();
Accids.push(tempString);
}
temp=null;
return Accids;
**/
}
return null;
}
else
{
Stack<Account> temp;
temp=seqRecords.getAccount(VIN);
if(temp==null || temp.isEmpty())
{
System.out.println("This VIN does not exist in the sequence");
return null;
}
else
{
return temp;
}
}
}
//driver method
public static void main(String[] args) throws Exception
{
CVR hello= new CVR(100);
try
{
//System.out.println("hello");
//hello.generate(5);
Account abdcg=new Account("adsj4jandnj4", "Muhammad Ferreira", "perfect record");
Account abdcg1=new Account("adsj4jandnj4","Myriam Ferreira", "Fender Bender");
Account abdcg2= new Account("adsj4jandnj4", null, null);
/////
hello.add("adsj4jandnj4", abdcg);
hello.add("adsj4jandnj4", abdcg2);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is my sequence class
import java.util.ArrayList;
import java.util.Stack;
public class sequence
{
private class position
{
private Stack<Account> stack;
private int index;
//constructors
public position()
{
this.stack=new Stack<Account>();
this.index=0;
}
public position(int index, Account acc)
{
this.index=index;
this.stack=new Stack<Account>();
stack.push(acc);
}
//muatators
public int getIndex()
{
return index;
}
public void setIndex(int index)
{
this.index=index;
}
public Stack<Account> getStack()
{
return stack;
}
public void setStack(Stack<Account> newStack)
{
this.stack=newStack;
}
}
private int size;
//private int tail;
private int elementsNum;
//private int currentIndex;
private ArrayList<position> Arr;
public sequence()
{
//currentIndex=0;
size=0;
Arr= new ArrayList<position>(); ;
}
//add first method
public void add(Account account)
{
for(int i=0; i<size; i++)
{
//if already in array, push into its stack
if((Arr.get(i).getStack().peek().getVIN()).equals(account.getVIN()))
{
Arr.get(i).getStack().push(account);
break;
}
//if not in array, make new entry for it
else if(!(Arr.get(i).getStack().peek().getVIN()).equals(account.getVIN()) && i==size-1)
{
position added=new position(size, account);
Arr.add(added);
//currentIndex++;
size++;
}
}
}
//addIndex
//don't think this method is necessary for assignment
/**
public void addIndex(int ind, Account account)
{
position added=new position(ind, account);
Arr.add(ind, added);
size++;
//update indexes of position node
updateIndex();
}
*/
//resizeArray and updates index
public void resize()
{
Arr.trimToSize();
updateIndex();
}
//remove method
public void removeVIN(String VIN)
{
for (int i=0; i<size; i++)
{
if(size==0 || (!VIN.equals(Arr.get(i).getStack().peek().getVIN()) && i==size-1))
{
System.out.println("The Sequence does not contain this VIN");
break;
}
else if(VIN.equals(Arr.get(i).getStack().peek().getVIN()))
{
Arr.remove(i);
resize();
size--;
System.out.println("Successfully removed " +VIN+" and associated values");
}
}
}
//update indexes
public void updateIndex()
{
for (int i=0; i<size; i++)
{
if(Arr.get(i).getIndex() != i)
{
Arr.get(i).setIndex(i);
}
}
}
//Get Values
//Will be used in CVR for both the getValues method (return all values)
//and prevAccids method (return only the accidents not entire account)
public Stack<Account> getAccount(String VIN)
{
for (int i=0; i<size; i++)
{
if(size==0)
{
System.out.println("The Sequence is empty");
break;
}
else if(VIN.equals(Arr.get(i).getStack().peek().getVIN()))
{
return Arr.get(i).getStack();
}
}
return null;
}
//get previous VIN method
public String preVIN(String VIN)
{
for (int i=0; i<size; i++)
{
if((Arr.get(i).getStack().peek().getVIN()).equals(VIN))
{
if(i==0)
{
return "There is no previous VIN, this is the first one";
}
return Arr.get(i-1).getStack().peek().getVIN();
}
}
return null;
}
//get next VIN method
public String nextVIN(String VIN)
{
for (int i=0; i<size; i++)
{
if((Arr.get(i).getStack().peek().getVIN()).equals(VIN))
{
if(i==size-1)
{
return "There is no next VIN, this is the last one";
}
return Arr.get(i+1).getStack().peek().getVIN();
}
}
return null;
}
}
Finally, this is my Account class
//this method is similar to a node, contains
//VIN, Owner, Accidents details
public class Account
{
private String VIN;
private String owner;
private String accidents;
public Account() {};
public Account(String VIN)
{
this.VIN=VIN;
this.owner=null;
this.accidents=null;
}
public Account(String VIN, String owner, String accidents)
{
this.VIN=VIN;
this.owner=owner;
this.accidents=accidents;
}
//mutators
public void setVIN(String VIN)
{
this.VIN=VIN;
}
public String getVIN()
{
return VIN;
}
public void setOwner(String owner)
{
this.owner=owner;
}
public String getOwner()
{
return owner;
}
public void setAccids(String accidents)
{
this.accidents=accidents;
}
public String getAccids()
{
return accidents;
}
}
You may want to use TreeMap instead of obsolete Hashtable - it is sorted by key by design and provides methods to get sequence of keys and related values:
K firstKey()
K lastKey()
K higherKey(K key)
K lowerKey(K key) etc.
I am trying to refactor this code I have below that uses several nested if statements to check if two list contains the same items.
List<Car> CarList = CarService.findCarByConfigtype(pageName);
for (int i = 0; i < CarList.size(); i++) {
System.out.println(CarRestApiController.data().getModel());
if (CarList.get(i).getModel().equals(CarRestApiController.data().getModel())) {
dataFound.add(CarList.get(i).getModel());
if (CarList.get(i).getDerivative().equals(CarRestApiController.data().getDerivative())) {
dataFound.add(CarList.get(i).getDerivative());
if (CarList.get(i).getSvp().equals(CarRestApiController.data().getSvp())) {
dataFound.add(CarList.get(i).getSvp());
if (CarList.get(i).getEngine().equals(CarRestApiController.data().getEngine())) {
dataFound.add(CarList.get(i).getEngine());
if (CarList.get(i).getFueltype().equals(CarRestApiController.data().getFueltype())) {
dataFound.add(CarList.get(i).getFueltype());
if (CarList.get(i).getBodystyle().equals(CarRestApiController.data().getBodystyle())) {
dataFound.add(CarList.get(i).getBodystyle());
if (CarList.get(i).getTransmission().equals(CarRestApiController.data().getTransmission())) {
dataFound.add(CarList.get(i).getTransmission());
if (CarList.get(i).getSalescategory().equals(CarRestApiController.data().getSalescategory())) {
dataFound.add(CarList.get(i).getSalescategory());
}
}
}
}
}
}
}
}
}
A solution could be to use Strategy design pattern. Have a strategy for each if statement, iterate over the list of strategies and process each car in the list
public interface CarFeatureStrategy {
boolean canProcess(Car carToProcess, Car carToMatch);
Object process(Car carToProcess);
}
The canHandle method should encapsulate the if statements which needs to be true to allow the processing and the process method should return the value of corresponding property of the car (for the example in the description there should be 8 strategies)
public class ModelStrategy implements CarFeatureStrategy {
#Override
public boolean canProcess(Car carToProcess, Car carToMatch) {
return carToProcess.getModel().equals(carToMatch.getModel));
}
#Override
public Object process(Car carToProcess) {
return carToProcess.getModel();
}
}
public class DerivativeStrategy implements CarFeatureStrategy {
#Override
public boolean canProcess(Car carToProcess, Car carToMatch) {
return carToProcess.getModel().equals(carToMatch.getModel())
&& carToProcess.getDerivative().equals(carToMatch.getDerivative());
}
#Override
public Object process(Car carToProcess) {
return carToProcess.getDerivative();
}
}
public class SvpStrategy implements CarFeatureStrategy {
#Override
public boolean canProcess(Car carToProcess, Car carToMatch) {
return carToProcess.getModel().equals(carToMatch.getModel())
&& carToProcess.getDerivative().equals(carToMatch.getDerivative())
&& carToProcess.getSvp().equals(carToMatch.getSvp());
}
#Override
public Object process(Car carToProcess) {
return carToProcess.getSvp();
}
}
// .... and so on for each condition which needs to be met
// EngineStrategy, FueltypeStrategy, BodystyleStrategy,
// TransmissionStrategy, SalescategoryStrategy
The CarProcessor retrieves the cars corresponding to the given pageName, retrieves the data from the CarRestApiController and uses the list of strategies to process the cars
public class CarProcessor {
private CarService carService;
private CarRestApiController restController;
private List<CarFeatureStrategy> carFeatureStrategies;
public void processCars(Object pageName) {
// for example purpose the list of strategies is initialized here,
// but it should be initialized somwhere where the initialization is done
// only once rather than each time the processCars method is called
carFeatureStrategies = new ArrayList<>();
carFeatureStrategies.add(new ModelStrategy());
carFeatureStrategies.add(new DerivativeStrategy());
carFeatureStrategies.add(new SvpStrategy());
// ....
// add to the strategies list an instance of each strategy to process
// the car
Car carToMatch = restController.data();
List<Car> cars = carService.findCarByConfigtype(pageName);
List<Object> dataFound = new ArrayList<>();
for (Car carToProcess : cars) {
for (CarFeatureStrategy carFeatureStrategy : carFeatureStrategies) {
if (carFeatureStrategy.canProcess(carToProcess, carToMatch)) {
dataFound.add(carFeatureStrategy.process(carToProcess));
}
}
}
}
}
The example could be optimised implementing the Chain of responsibility design pattern. With a chain of responsibility the if statements in the canHandle methods will simplify to only one boolean condition per strategy.
For chain of responsibility the strategies have to be enhanced with a method to return the next strategy in the chain
public interface CarFeatureStrategy {
boolean canProcess(Car carToProcess, Car carToMatch);
Object process(Car carToProcess);
CarFeatureStrategy next();
}
the strategy implementations have to be enhanced with a reference to the next strategy in the chain
public class ModelStrategy implements CarFeatureStrategy {
private CarFeatureStrategy nextStrategy;
public ModelStrategy(CarFeatureStrategy nextStrategy) {
this.nextStrategy = nextStrategy;
}
#Override
public boolean canProcess(Car carToProcess, Car carToMatch) {
// check only the model
return carToProcess.getModel().equals(carToMatch.getModel));
}
#Override
public Object process(Car carToProcess) {
return carToProcess.getModel();
}
#Override
public CarFeatureStrategy next() {
return this.nextStrategy;
}
}
public class DerivativeStrategy implements CarFeatureStrategy {
private CarFeatureStrategy nextStrategy;
public DerivativeStrategy(CarFeatureStrategy nextStrategy) {
this.nextStrategy = nextStrategy;
}
#Override
public boolean canProcess(Car carToProcess, Car carToMatch) {
// check only the derivative property
return carToProcess.getDerivative().equals(carToMatch.getDerivative());
}
#Override
public Object process(Car carToProcess) {
return carToProcess.getDerivative();
}
#Override
public CarFeatureStrategy next() {
return this.nextStrategy;
}
}
// ... and so on for all the strategies
The CarProcessor should build a chain of strategies and process each car until the chain is finished (the next method of current strategy returns null) or the current strategy cannot process the current car (canHandle method of current strategy returns false)
public class CarProcessor {
private CarService carService;
private CarRestApiController restController;
public void processCars(Object pageName) {
// for example purpose the chain of responsibilities is initialized here,
// but it should be initialized somwhere where the initialization is done
// only once rather than each time the processCars method is called
// initialise the chain of responsibilities in revers order
CarFeatureStrategy salesCategoryStrategy = new SalescategoryStrategy(null);
CarFeatureStrategy transmissionStrategy = new TransmissionStrategy(salesCategoryStrategy);
CarFeatureStrategy bodystyleStrategy = new BodystyleStrategy(transmissionStrategy);
CarFeatureStrategy fueltypeStrategy = new FueltypeStrategy(bodystyleStrategy);
CarFeatureStrategy engineStrategy = new EngineStrategy(fueltypeStrategy);
// .... and so on until the first strategy in the chain
CarFeatureStrategy modelStrategy = new ModelStrategy(...);
Car carToMatch = restController.data();
List<Car> cars = carService.findCarByConfigtype(pageName);
List<Object> dataFound = new ArrayList<>();
for (Car carToProcess : cars) {
CarFeatureStrategy currentStrategy = modelStrategy;
do {
if ( !currentStrategy.canProcess(carToProcess, carToMatch)) {
// if current strategy cannot process the current car
// stop the chain
break;
}
dataFound.add(currentStrategy.process(carToProcess));
// move to the next strategy in the chain
currentStrategy = currentStrategy.next();
} while (currentStrategy != null)
}
}
}
I would first save the result of CarList.get(i) and CarRestApiController.data() to variables as #T.J.Crowder suggested. Then I would flip the if-checks and use continue to get rid of the nesting. Like this:
List<Car> carList = CarService.findCarByConfigtype(pageName);
for (int i = 0; i < carList.size(); i++) {
Car apiData = CarRestApiController.data();
Car carListData = carList.get(i);
System.out.println(CarRestApiController.data().getModel());
if (!carListData.getModel().equals(apiData.getModel())) {
continue;
}
dataFound.add(carListData.getModel());
if (!carListData.getDerivative().equals(apiData.getDerivative())) {
continue;
}
dataFound.add(carListData.getDerivative());
if (!carListData.getSvp().equals(apiData.getSvp())) {
continue;
}
dataFound.add(carListData.getSvp());
// ... and so on.
}
I'm creating a FriendList which extends ArrayList and is populated with a Friend object. However when I try accessing methods normally available to Friend, the compiler says it cannot resolve the method - in this case compareTo(Friend).
FriendList class:
public class FriendList<Friend> extends ArrayList<Friend> {
private boolean isAdded;
public FriendList() {
isAdded = false;
}
public void alphabetAdd(Friend friend) {
if (this.isEmpty()) {
add(friend);
return;
}
int index = 0;
// add friends alphabetically
while (!isAdded) {
Friend f = this.get(index+1);
if (f.compareTo(friend) < 0) {
index++;
} else {
this.add(index, friend);
isAdded = true;
}
}
}
}
Friend class:
public class Friend implements Comparable<Friend> {
// constructors and other methods work fine - just need to see compareTo
// #Override
public int compareTo(#NonNull Friend o) {
String name1 = getUserFirstName() + getUserLastName();
Friend f;
if (o instanceof Friend) {
f = (Friend) o;
String name2 = f.getUserFirstName() + f.getUserLastName();
if (name1.compareTo(name2) < 0)
return -1;
else if (name1.compareTo(name2) > 0)
return 1;
}
return 0;
}
}
The issue is in FriendList<Friend>. This is treated as a declaration of generic class like FriendList<T> and Friend becomes not an actual type but an alias that is why only methods declared in Object are available.
Change declaration of your class to
public class FriendList extends ArrayList<Friend>
I have been working very hard to attempt and figure out these lines of code, but I can never seem to get it to come out right. I get several errors on lines 86, 91, 100, 110 and 118 and I have absolutely no idea why. Anyway, here it is:
public class lab21composition
{
public static void main(String args[])
{
CarFactory factory = new CarFactory ("Ford");
Garage myGarage = new Garage();
Car c = factory.produceCar("Fusion");
Truck t = factory.produceTruck("F150");
System.out.println(myGarage);
myGarage.addVehicle(c);
System.out.println(myGarage);
myGarage.addVehicle(t);
System.out.println(myGarage);
Vehicle v = myGarage.removeVehicle();
if (null !=v)
{
System.out.println(v.toString() + " was removed from garage.");
System.out.println(myGarage);
}
else
{
System.out.println("There was no vehicle in the garage to remove.");
}
myGarage.addVehicle(t);
System.out.println(myGarage);
CarFactory factory2 = new CarFactory ("Honda");
Garage myGarage2 = new Garage();
Car d = factory.produceCar("Odyssy");
myGarage.addVehicle(d);
System.out.println(myGarage2);
}
}
class CarFactory
{
private String name;
public CarFactory(String n)
{
name = n;
}
public Car produceCar(String model)
{
return name;
}
public Truck produceTruck(String model)
{
return name;
}
}
class Vehicle
{
private String make, model;
public Vehicle()
{
make = "Undefined";
model = "Undefined";
}
public Vehicle(String _make, String _model)
{
make = _make;
model = _model;
}
public String toString()
{
return make+" "+model;
}
}
class Car extends Vehicle
{
super (_make,_model); //I get a illegal start of type and identifier expected error here
}
class Truck extends Vehicle
{
super (_make,_model); //I get a illegal start of type and identifier expected error here
}
class Garage
{
//define a private variable that holds a Vehicle object. This will represent
private String Veh;
// the vehicle being stored in the Garage. If the garage is empty, then this variable should be null
}
public void addVehicle(Vehicle v)
{
if(v==Veh) /* replace FALSE with code to check if v is the same as vehicle */
{
//HINT: use a function inherited from the Object class!
System.out.println(v.toString() + " is already parked in this garage")
}
else if (hasVehicle())
{
System.out.println("This garage is full!");
}
else
{
//store the vehicle that was passed to this function
//in this class vehicle attribute
}
}
class removeVehicle()
{
public Vehicle removeVehicle()
{
//store this class vehicle attribute in a temporary variable
// set this class vehicle attribute to null
// return the vehicle stored in the temporary variable
return null;
}
public boolean hasVehicle()
{
//change this return statement so that it
//returns an appropriate boolean value
return false;
}
public String toString()
{
if (hasVehicle())
{
//replace ??? with the toString() method of the vehicle
// that is in this garage
return "This garage has a ??? in it!";
}
else
{
return "This garage is empty.";
}
}
}
class Car extends Vehicle
{
super (_make,_model);
}
The above super call appears outside a constructor. This is syntactically invalid code.
Solution 1: delete this code.
Solution 2: write a constructor.
I really don't understand the principle of Object Oriented Design??
So I have classes
Map class holds rooms and connects all of rooms , places all of hazards randomly into rooms, return the particulate room, and return the random rooms.
and
Player class that play turns, move player from room to another, shoot into rooms and play games.
also
Room class as follow.
import java.util.ArrayList;
public class Room
{
private int myRoomID;
private ArrayList<Room> myNeighbours;
private boolean myHasBats;
private boolean myHasPit;
private boolean myHasWumpus;
public Room(int id) {
myRoomID = id;
myNeighbours = new ArrayList<Room>();
}
public int getRoomID() {
return myRoomID;
}
public ArrayList<Room> getNeighbours() {
return myNeighbours;
}
public void connectTo(Room room) {
myNeighbours.add(room);
}
public boolean hasBats() {
return myHasBats;
}
public void setHasBats(boolean flag) {
myHasBats = flag;
}
public boolean hasPit() {
return myHasPit;
}
public void setHasPit(boolean flag) {
myHasPit = flag;
}
public boolean hasWumpus() {
return myHasWumpus;
}
public void setHasWumpus(boolean flag) {
myHasWumpus = flag;
}
public void checkBats() {
boolean bats = false;
for (Room r : myNeighbours) {
if (r.hasBats()) {
bats = true;
}
}
if (bats) {
System.out.println("I hear squeaking!");
}
}
public void checkPit() {
boolean pit = false;
for (Room r : myNeighbours) {
if (r.hasPit()) {
pit = true;
}
}
if (pit) {
System.out.println("I feel a draft!");
}
}
public void checkWumpus() {
boolean wumpus = false;
for (Room r : myNeighbours) {
if (r.hasWumpus()) {
wumpus = true;
}
}
if (wumpus) {
System.out.println("I smell a wumpus!");
}
}
public boolean enter(Player player) {
System.out.println("You are in Room " + myRoomID);
System.out.print("Exits lead to rooms");
for (Room r : myNeighbours) {
System.out.print(" " + r.getRoomID());
}
System.out.println();
checkBats();
checkPit();
checkWumpus();
if (myHasBats) {
System.out.println("A flock of bats picks you up and carries you off to another room!");
return player.moveRandom();
}
else if (myHasPit) {
System.out.println("You fall into a bottomless pit!");
return true;
}
else if (myHasWumpus) {
System.out.println("You have been eaten by a wumpus!");
return true;
}
return false;
}
public boolean shoot()
if (myHasWumpus) {
System.out.println("You killed the Wumpus!");
return true;
}
else {
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
}
And I want to change this so that the wumpus needs to be shot more than once (you choose how many times) to be killed. Each time it is shot it runs to a random neighbouring room (not the one the player is in).
I am assuming that I need to change public boolean shoot() method into loop and call public Room getRandomRoom() as below.
But I really don't understand how to do this, especially because the use of boolean method is very confusing to me.
Does anyone know where I can find a information to learn the basic's of Object Oriented Design?
public Room getRandomRoom() {
Random rng = new Random();
int i = rng.nextInt(Map.NUM_ROOMS);
return myRooms.get(i);
}
Later on we are going to use implements in the class to separate all of hazards into classes. but for not they are all in Map and Room class.
Well without a wumpus class that's going to be messy and limited and even more inefficient. Your problem isn't that you don't get OO, it's that you are being restricted from using it.
Without out the class.
You are goingto have to add a myWumpusShotCount to room
Then in your shoot function, add 1 to it, test to see if it's 3 and if so kill it else random choose a room and set hasWumpus and WumpusShotCount in it
If you had a wumpus class it would have a property room , and another for how many bullets it had shipped and a behaviour when shot, ie the state of the wumpus and the behaviours of wumpus would be implemented by wumpus, not room. That's OO.
With the help of Tony Hopkinson, I have come up with this code but it doesn't compile yet. It says can not find symbol - method getRandomRoom() To call the methodgetRandomRoom();` from Map class.
To send wumpus to the room another room randomly
public boolean shoot() {
if (myHasWumpus) {
myWumpusShotCount = 3;
for(int i = 0; i< myWumpusShotCount; i++){
if(myWumpusShotCount<=i){
System.out.println("You killed the Wumpus!");
return true;
}
else {
Room wRoom = getRandomRoom();
System.out.println("You killed the Wumpus!");
return false;
myWumpusShotCount++;
}
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}
System.out.println("You killed the Wumpus!");
return true;
}
}
System.out.println("Your arrow falls with a clatter to the floor!");
return false;
}