aspose file tools*
The moose likes Beginning Java and the fly likes programming to the interface Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "programming to the interface" Watch "programming to the interface" New topic
Author

programming to the interface

Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
I need some advice with an exercise that I am doing which I have got stuck with and can not get past what ever I try so was hoping that someone may be able to help. My tutor says I am very close but it does not feel like it!

I need to implement a method called reset()

this method should return a new empty TrafficQueue (which is designed as an ArrayList) the same size as the current one.

I must stick to the method signatures specified in the interface, so must use

public ThingBeingSimulated reset() {
...
}

The class ThingBeingSimulated is a programme that I have been give to allow the TrafficQueue to be shown on the screen. TrafficQueue is the class and queue should be the instance of the class. I have tried all of the following which give a range of compilation errors.

public ThingBeingSimulated reset(){
return this.queue(size);
}

public ThingBeingSimulated reset(){
return new TrafficQueue(size);}

public ThingBeingSimulated reset(){
return new TrafficQueue(queue.size);}

public ThingBeingSimulated reset(){
return new queue(queue.size):}

public ThingBeingSimulated reset(){
queue = new ArrayList<RoadVehicle>(size);
return queue(size);
}

public ThingBeingSimulated reset(){
return new ThingBeingSimulated(queue.size);}

I would be grateful for any help what so ever.





Mike Noel
Ranch Hand

Joined: Dec 15, 2005
Posts: 108
Notice that the return type for the reset function is ThingBeingSimulated. It won't be possible for the reset() method to return a TrafficQueue object unless there is a super class/sub class relationship between ThingBeingSimulated and TrafficQueue. If there was that relationship then your example would have worked. I'm guessing that the requirements are slightly different than what you think. Maybe they want you to return a ThingBeingSimulated where the queue inside (this.queue) is empty. Or maybe the TrafficQueue is a member of ThingBeingSimulated and you're supposed to zero out that member.

_M_


Mike Noel
Jeff Albertson
Ranch Hand

Joined: Sep 16, 2005
Posts: 1780
Oh boy, some of your attempts show a loose grip on Java syntax: if queue is a variable, why are you writing "new queue" or "queue(size)"? I think you need to review basic syntax, but your instructor seems to think you can handle generic collections -- which one is it?


There is no emoticon for what I am feeling!
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Sorry Fred for posting in the intermediate box I am new to this and did not realise it was not allowed.

Thanks to you both for your response.

To clarify the instance queue is an ArrayList which takes objects of the type RoadVehicle. Queue is an object in the class TrafficQueue. I need to pass the instance queue to the interface ThingBeingSimulated. The ThingBeingSimulated class then shows a representation of the queue on the screen or at least I think that is what it should do.

What I am confused about is if the return type I am being told to use is ThingBeingSimulated how does this related to the return I have also been told I need which is a new empty ArrayList of the same size as the one setup in queue.

I feel like I am going round in circles getting no where so if any one can suggest a good tutorial, web site or book for syntax and particularly collections that might help I would be greatful.
Thanks
Martin Mathis
Ranch Hand

Joined: Dec 20, 2004
Posts: 45
This is kind of confusing. You have TrafficQueue which you say is designed as an ArrayList, and you have ThingBeingSimulated.

I'm assuming that ThingBeingSimulated is the interface that TrafficQueue implements.

So is TrafficQueue an actual implementation of an ArrayList, or does it just have an ArrayList member in it. Either way, I don't think it makes sense for a reset() command to return an object of the same type as the one you're calling it on. It seems like you'd simply want to empty (create a new) ArrayList inside the TrafficQueue and return nothing...
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
You seem to have a confusion about ThingBeingSimulated, calling it an interface and a class. I suggest you post the code for it or, if it isn't available, its API documentation.


SCJP 1.4, SCWCD 1.3, SCBCD 1.3
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11499
    
  16

It's not a big deal. Besides, it gives us bartenders and sheriffs something to do!!!

Whatever you do, keep asking questions here. we all love to help people, but remember we're all volunteers, so sometimes it takes a little while before you get your answers.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Someone has suggested that I post the code or documentation. Is there a way of attaching files to this discussion board?

In case there is not I have pasted the doc's for the simplesim package I have been given.

Package simplesim
Interface Summary
TBSModel Interface which must be implemented by any class which provides the underlying functionality (model) of a ThingBeingSimulated.
TBSView Interface which should be implemented by any class which implements a view of a TBS - i.e.
ThingBeingSimulated Interface which should be implemented by any class which forms a Thing Being Simulated.

simplesim
Interface TBSModel
All Known Subinterfaces:
ThingBeingSimulated

--------------------------------------------------------------------------------

public interface TBSModelInterface which must be implemented by any class which provides the underlying functionality (model) of a ThingBeingSimulated.




--------------------------------------------------------------------------------

Method Summary
ThingBeingSimulated reset()
Return a TBS which is the desired result when the user hits reset, typically A TBS in an initial state.
void simstep()
Perform a step of simulation.


Method Detail


simstep
void simstep()
throws SimulationExceptionPerform a step of simulation. If this fails for some reason, a SimulationException is thrown. This has the effect of showing a dialog to the user containing the result of getMessage(). Therefore when the exception is thrown it should be initialised with a suitable message string, typically dirived from a TBS-specific exception.

Throws:
SimulationException

--------------------------------------------------------------------------------

reset
ThingBeingSimulated reset()Return a TBS which is the desired result when the user hits reset, typically A TBS in an initial state.


--------------------------------------------------------------------------------


simplesim
Interface TBSView
All Known Subinterfaces:
ThingBeingSimulated

--------------------------------------------------------------------------------

public interface TBSViewInterface which should be implemented by any class which implements a view of a TBS - i.e. a way of displaying it to the user.




--------------------------------------------------------------------------------

Method Summary
void display(java.awt.Graphics g)
Display the TBS on the screen.
void setBounds(int maxX, int maxY)
Set the bounds within which the TBS is displayed, 0...maxX by 0..maxY This is called before each call to display, so that if e.g.


Method Detail


display
void display(java.awt.Graphics g)Display the TBS on the screen. This is called whenever the display needs to be redrawn, including when the GUI is initialised and after every simstep().


--------------------------------------------------------------------------------

setBounds
void setBounds(int maxX,
int maxY)Set the bounds within which the TBS is displayed, 0...maxX by 0..maxY This is called before each call to display, so that if e.g. the window is resized, display() can use this information to size the representation of the TBS accordingly.


I am not sure if this next part is correct as I can not find any doc's for "serializable"
Serialized Form

--------------------------------------------------------------------------------
Package simplesim

Class simplesim.DisplayPanel extends javax.swing.JPanel implements Serializable


Serialized Fields


parent
SimulationFrame parentClass simplesim.QuitableJFrame extends javax.swing.JFrame implements Serializable



Class simplesim.SimulationControlPanel extends javax.swing.JPanel implements Serializable



Class simplesim.SimulationException extends java.lang.Exception implements Serializable



Class simplesim.SimulationFrame extends QuitableJFrame implements Serializable


Serialized Fields


theThingBeingSimulated
ThingBeingSimulated theThingBeingSimulated
--------------------------------------------------------------------------------

menubar
SimulationMenuBar menubar
--------------------------------------------------------------------------------

handler
SimulationEventHandler handler
--------------------------------------------------------------------------------

displayPanel
DisplayPanel displayPanel
--------------------------------------------------------------------------------

controlPanel
SimulationControlPanel controlPanelClass simplesim.SimulationMenuBar extends javax.swing.JMenuBar implements Serializable


Serialized Fields


fileMenu
javax.swing.JMenu fileMenu
--------------------------------------------------------------------------------

lfMenu
javax.swing.JMenu lfMenu




If there is a better way of displaying thd doc's please let me know as simply copy and pasting to this disscussion board all the formating is lost.

Hope this might help someone explain to me what I need to return in the reset() method. I think I need a new instance of a TrafficQueue and need to make this an empty ArrayList that will take RoadVehicle objects, and that it needs to have the same number of elements as the original TrafficQueue. The constructor for TrafficQueue takes size as its parameter so I thought if I create a new instance of TrafficQueue and pass it the size required and then return this object that should work.

I need to first understand what I need to do and then work out how to code it so help at any leave would be appriciated.

Best wishes
Dianne
Martin Mathis
Ranch Hand

Joined: Dec 20, 2004
Posts: 45
I don't really see why reset should create a new ThingBeingSimulated instead of.... actually resetting the current one, but I guess that's how its designed.

If that's the case, the following should be fine, provided TrafficQueue implements ThingBeingSimulated.

Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
So, ThingBeingSimulated is an interface. You can't pass an ArrayList as a return type as you cannot say that an ArrayList IS-A ThingBeingSimulated.

There is some documentation missing. You need to return an object whose class implements ThingBeingSimulated.
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Roger said
"There is some documentation missing. You need to return an object whose
class implements ThingBeingSimulated."

Can you tell me how to attached a file? I could then attach the whole
zipped directory.

I have been told to say in the TrafficQueue class that

TrafficQueue implements ThingBeingSimulated

so I think that will allow me to return the TrafficQueue from the reset()
method.


I have tried what Martin advised and thought that it might work as my constructor for the TrafficQueue is as follows

public TrafficQueue(int size){
queue = new ArrayList<RoadVehicle> (size);
for (int i = 0; i < queue.size(); i ++)
queue.add(null);
count = 0;
}

Then since TrafficQueue implememts ThingBeingSimulated I simply make a new TrafficQueue object and pass it size of the queue needed as he said

public ThingBeingSimulated reset(){ return new TrafficQueue(size);}


However I still get the dreaded abstract warning and the compiler also complains about not being able to find the variable size.

---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:13: TrafficQueue is not abstract and does not override abstract method simstep() in simplesim.TBSModel
public class TrafficQueue implements ThingBeingSimulated{
^
TrafficQueue.java:50: cannot find symbol
symbol : variable size
location: class TrafficQueue
return new TrafficQueue (size);
^
2 errors
> Terminated with exit code 1.

I will perserve with this and try to check the code before reset() method just incase there is something wrong above.

Many thanks to everyone for there help so far. I did not realise that there where sites like this available and it has made me more enthusiasic to learn Java.

Apologise to the experienced programmers for irritating them with my poor grasp of Jave syntax but please keep the messages coming.

Best wishes
Dianne
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Hey,

You need to have a method in TrafficQueue which overrides simstep() in TBSModel, ie. you need to have a method called simstep() in TrafficQueue with a method body. Like this:

public void simstep()
{
// whatever this method has to do
}

This non abstract method MUST have the same return type AND signature (the params of a method) as the abstract method found in TBSModel AND the same name.
Because this class TrafficQueue implements the abstraction defined in TBSModel, it must be a full implementation of it.
Overriding is when a subclass defines a method of the same type and signature (type & num of params) as the superclass so that it can be extended and speciliased.
Don't confuse this with overloading.

The other error seems to be that you haven't declared variable size.

So, supposing its an int write this: int size = 0, before you use it.

Merry Christmas,

Dani

[ December 23, 2005: Message edited by: Dani Atrei ]
[ December 23, 2005: Message edited by: Dani Atrei ]

Si altas son las torres, el valor es alto - Alberti
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Dear All

Thanks for the help, I have managed to get a little further. I have included

public ThingBeingSimulated reset(){
int size =0;
return new TrafficQueue (size);
}

AND

public void simstep(){}


I think there is something that I do not understand about pasing the size of the array. I have tried to call my reset method and then print the TrafficQueue object queue1 to see if the ArrayList is empty. The compiler does not like the fact I am passing an int to my reset method. In the details of the method there were no parameters passed to the method as () was empty. If I simiply use queue1.reset it compiles but does not reset the queue.

I will need to consider passing the size variable.

This is the error message I get when I try

queue1.reset(10);
System.out.println(queue1);

> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:152: reset() in TrafficQueue cannot be applied to (int)
queue1.reset(10);
^
Merry Christmas
Everyone

Dianne Gerrelli
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Hey Dianne,

You're trying to pass an int to a method which has no parameters. If you want to call Q.reset(10); then you need to specify that the method reset will take an int as param:

public ThingBeingSimulated reset(int size)
{
// whatever this does
}

Also, i m not sure what you re trying to pass into the arraylist, but it only takes objects, it won t hold primitives.
If you want to use an ArrayList, you need to make an



To use the ArrayList, you first need to declare a variable which will hold an ArrayList reference (ie. a pointer to the arraylist you declared somewhere in memory). You also need to instantiate an ArrayList obj, and then use it:




If you want to add an int to an ArrayList, you need to create an object that represents that int, ie Integer. Here with new Integer, I instantiate an Integer object and pass an int 12 into the constructor so that the Integer object will hold in 12.

Merry Christmas again,

Dan
[ December 24, 2005: Message edited by: Dani Atrei ]
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Many thanks for your suggestion.

I am a like confused about how specific method signatures are. I have been told to use

public ThingBeingSimulated reset(){
}

So because there were no parameters I was assuming I would need to pass the size of the arrayList into the reset method some other way. There is a method in the ArrayList documentation which is
public int size(){

}

I was therefore thinking of calling this from within my reset() method.

Can you please let me know if the method signature says no parameters ie () am I allowed to change it and pass in (int size) where size will be the number of elements in the ArrayList?

Best wishes
Dianne
Roger Chung-Wee
Ranch Hand

Joined: Sep 29, 2002
Posts: 1683
This is what you need to do. In the reset() method, instantiate TrafficQueue, populate it and return it. That's all!
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Howdi,

No parameters means the method doesn t accept parameters, so you can t pass it parameters.
Now the size() method has no parameters, but it returns an int. So if you have an arraylist with 10 elements, it s going to return 10.

Signature (if i remember well) refers to the parameters the method can accept, the number, types and names.
Return type is what type the method will return, so if a method is of type int, it can t return a string.

You don t need to pass the size, you can ask it inside the reset method as Roger says. Just make sure the ArrayList is in scope. If it s in the class scope, then do something like this:



Dan
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Dear All.

I have managed to make some more progress with my attempt to produce an ArrayList to demonstrate a random collection of trafficVehicles in a queue, I belive this is know as FIFO list. However although the programme works it does not seem to implement the TBS interface that I have been given. I have been told to do this using

public void simstep(){}

This method is designed to; "Perform a step of simulation. If this fails for some reason, a SimulationException is thrown. This has the effect of showing a dialog to the user containing the result of getMessage(). Therefore when the exception is thrown it should be initialised with a suitable message string, typically dirived from a TBS-specific exception."

What I need to do is
1.test if the queue is full
2. if it is remove the first vehicle
3. if the queue is not full, get a random vehicle from a list and add it to the end of the queue
4. then print a summary of the queue and the last vehicle added.

I have been able to test this all in my main method so I know that the code does work. The problem I am having is getting this to work inside the simstep method.

public void simstep(){
if (isFull())
{queue.remove(0);
}
else
{queue.add(roadVehicle);
count ++;
}
}

The call to the add() method produces compilation errors.
---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:42: cannot find symbol
symbol : variable roadVehicle
location: class TrafficQueue
{queue.add(roadVehicle);
^
1 error
> Terminated with exit code 1.

I have seen othere programmes using the following incantation

queue.add(new roadVehicle());

But it simply produces a different error message.
---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:43: cannot find symbol
symbol : class roadVehicle
location: class TrafficQueue
queue.add(new roadVehicle());
^
1 error
> Terminated with exit code 1.

I have 4 classes which extend the class RoadVehicle and since I am being told to add things randomly I need to beable to instruct the add() method to add objects of the type RoadVehicle to my Trafficqueue.

I am not sure if this may be a problem of visiblity between may classes as the messages say can not find symbol, so I have tried to make as much as possible public, but this has not helped.

Can someone please explain the compilation errors messages and let me know what the correct call to insert a RoadVehicle into the ArrayList queue.

Best wishes
Dianne Gerrelli

PS I have pasted the TrafficQueue class below but not the other programmes


import java.util.ArrayList;
import java.util.Random;
import java.lang.Exception;
import java.awt.Graphics;
import java.lang.Object;
import simplesim.*;


public class TrafficQueue implements ThingBeingSimulated{

/** Methods from TBSModel*/
public void display (Graphics g) {};
public void setBounds(int maxX, int maxY) {};

/**Class variables*/
private ArrayList<RoadVehicle> queue;
private int count;

/**Constructor for class*/
public TrafficQueue(int size){
queue = new ArrayList<RoadVehicle> (size);
for (int i = 0; i < queue.size(); i ++)
queue.add(null);
count = 0;
}

/**Method to return empty arrayList*/
public ThingBeingSimulated reset(){
int size =0;
return new TrafficQueue (size);
}

/** Method to initiate simulation of TBS interface*/
public void simstep(){
if (isFull())
{queue.remove(0);
}
else
{/**queue.add(roadVehicle);*/
queue.add(new roadVehicle());
count ++;
}
}


/**Method to test if the TrafficQueue is empty */
public boolean isEmpty (){
return (count == 0);
}

/**Method to test if the TrafficQueue is full */
public boolean isFull (){
return (queue.size() > count);
}

/**Method to get the size of the TrafficQueue */
public int size(){
int size =0;
return size;
}

/**Method to get an object at a particular index in the TrafficQueue */
public Object get(int index){
return queue;
}

/** Method to add a roadVehicle from the arrayList*/
public void add( RoadVehicle roadVehicle)
throws QueueFullException{
if (isFull())
{throw new QueueFullException(queue.size());}
else
{queue.add(roadVehicle);
count ++;
}
}

/**Method to remove a roadVehicle from the arrayList*/
public RoadVehicle remove (int index)
throws RuntimeException {
if (isEmpty())
throw new RuntimeException ("RuntimeExceptio: attempting to remove from empty queue");
else{
count = count-1;
}
return queue.remove(0);
}


/**Method to prints the number of RoadVehicles in the TrafficQueue */
public String toString(){
int lastinqueue = queue.size();
String queueRoadVehicle = "The last RoadVehicle added is " + queue.get(lastinqueue-1) + "\n";
queueRoadVehicle+=this.queue;
return queueRoadVehicle;
}

/**Main method which creates and populates two arrays */
public static void main (String [] args){

/**Creating 10 RoadVehicle objects of type Car, Bus and GoodsVehicle*/
Car car1 = new Car ("C", "Ford", "Yellow");
Car car2 = new Car ("C", "Mini", "White");
Car car3 = new Car ("C", "Ferrari", "Cream");
Car car4 = new Car ("C", "Poche", "Orange");
Bus bus1 = new Bus ("B", "Blue", 30);
Bus bus2 = new Bus ("B", "Grey", 15);
FireEngine fireEngine1 = new FireEngine ("F", "Standard", " red ");
FireEngine fireEngine2 = new FireEngine ("F", "Green Goddess", " green ");
GoodsVehicle goodsVehicle1 = new GoodsVehicle ("G", "green", " van ",4200);
GoodsVehicle goodsVehicle2 = new GoodsVehicle ("G", "black", " lorry ",6000);

TrafficQueue queue1 = new TrafficQueue (20);
Random generator = new Random();
RoadVehicle[] someVehicles = {car1, car2, car3, car4, bus1, bus2, goodsVehicle1, goodsVehicle2,fireEngine1,fireEngine2};

try {for (int i =0; i<8; i++) {
int randomIndex = generator.nextInt( 9);
queue1.add(someVehicles[randomIndex]);
}
System.out.println(queue1);
}
catch(QueueFullException e){
System.out.println(e.getMessage ()+"queue1");
}
finally{
System.out.println("the end");
}

}
}
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Hmm, from a quick look there's a problem with new roadVehicle(). RoadVehicle is a class that you want to instantiate (make an object of). It should be



The problem is that the compiler is trying to find out where the variable roadVehicle is declared. Classes start with a capital letter. So if you write what i wrote above it should work.

I'll look at it in more detail to see if i can find more to it than that, but now i have no time. This should be a step forward, post if you get new errors after this change.

Dan
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Thanks, I will try this and get back to you.

Best wishes
Dianne
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
I tried altering my call to my add method as follows
queue.add (new RoadVehicle());

but still got error messages
---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:43: RoadVehicle is abstract; cannot be instantiated
{queue.add (new RoadVehicle());
^
1 error
> Terminated with exit code 1.

So instead I have tried to move the code I was testing in main to within the simstep() method as shown below. I think this might get arround the initial problem as I copy the vehicles into an array and then randomly select them for insertion into the ArrayList.


/** Method to initiate simulation of TBS interface*/

public void simstep(){

if (isFull()){
queue.remove(0);
}
else
{Car car1 = new Car ("C", "Ford", "Yellow");
Bus bus1 = new Bus ("B", "Blue", 30);
FireEngine fireEngine1 = new FireEngine ("F", "Standard", "red");
GoodsVehicle goodsVehicle1 = new GoodsVehicle ("G", "green","van",4200);

TrafficQueue queue1 = new TrafficQueue (10);
Random generator = new Random();
RoadVehicle[] someVehicles = {car1, bus1, goodsVehicle1, fireEngine1};

try {for (int i =0; i<8; i++) {
int randomIndex = generator.nextInt(10);
queue1.add(someVehicles[randomIndex]);
count ++;
}
System.out.println(queue1);
}
catch(QueueFullException e){
System.out.println(e.getMessage ()+"queue1");
}
finally{
System.out.println("the end");
}
}
}


This compiles with no error messages but I am not sure of how to call this method into action. I assume I need to put a call within main.But when I call the method using

simstep();

I get the following error message which I do not understand

---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:130: non-static method simstep() cannot be referenced from a static context
simstep();
^
1 error
> Terminated with exit code 1.

I think I may be disappearing into a black hole !!!





Best wishes
Dianne Gerrelli
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
You can t instantiate abstract classes, because they're abstract, ie they don't define something concretely.
An abstract class is a partial definition of a class.
A class is like a blue print (like an architect map), it defines variable attributes and methods (state & behaviour).
An object is a living representation of a class. It has a state, can request services from other objects and has responsibility to provide certain services as defined in the class.

If simstep() should add an object of type RoadVehicle, then one way of doing it would be to have the simstep() method accept a RoadVehicle object. So the method would end up like this:


The reason for this is that the subclasses of the abstract class RoadVehicle share a common thing: they are all road vehicles (their type is the same -> RoadVehicle). The method expects an object of the RoadVehicle type, so you can pass Car, Truck etc...
Now, the part calling the simstep method (let s say the main method) would look something like this:



Now for your other error, i ve had it already many times, but stupidly enough i can t remember what exactly caused it. What i think you did was to call simstep() just like this in the main method. To call a object's method, you first need to instantiate it, you need to make an object from a class, so then you can use that object. Look at the code from the main method i gave you, it shows the instantiation of a TrafficQueue type object.

I've got other stuff i'd like to pick about your code, but i ll wait a bit.

I think I may be disappearing into a black hole !!!


Don't worry, it's going to work, it just takes a little time, it will end up making sense. And then:
!

Dan
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
I think this ThingBeingSimulated (TBS)may work in a slightly different way to the one you are suggesting, however I could always be wrong!

I have been given some alternative code which should implement TBS although my tormenters have told me that this will need to be altered "slightly" before it will work. I have pasted it below.

I have checked simstep() method and it once again does not take any parameters, so I do not think I am allowed to pass (RoadVehicle roadvehicle) into this method.

Also what confuses me is that simstep is not called within main, discribed below as the test programme.

When I have my programme finished I have been told to use the following test programme

import simplesim.*;

public class Test {
public static void main (String[] args) {
TrafficQueue q = new TrafficQueue (20);
SimulationFrame f = new SimulationFrame (500, 400, q);
f.setVisible(true);
}
}

I have assume this should be put into my main method, but since I can not find the correct way to call my add method within the simstep () I am stuck.

I have been considering this problem and realise that my add method can take parameters

public void add( RoadVehicle roadVehicle)

and this works when using
queue.add(roadVehicle);

so I was wondering why I can not just call the add method from within the simstep () but this does not work either.

My main problem is that I have a very bad cold at present and therefore can not seem to concentrate, so I am sorry if I am rambling.

Best wishes
Dianne Gerrelli



ANOTHER EXAMPLE OF A PROGRAMME IMPLEMENTING THE TBS
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
import gensim.*;
import simplesim.*;

/**
* Class containing multiple number sequences. Since this
* implements ThingBeingSimulated, it needs to keep track of
* the current step number, current value of each sequence etc.
* as well as simply containing the sequences themselves.
*/
public class SetOfNumberSequences implements ThingBeingSimulated {

private ArrayList theSequences;

// Current step number
private int n = 1;
private int stepCounter = 0;

// Boundary within which we'll display the sequences.
private int minX, minY, maxX, maxY;

// Current value of each sequence
private long[] sequenceValue;

/**
* Constructor to create an empty SONS.
*/
public SetOfNumberSequences() {
theSequences = new ArrayList();
// This will work in practice, although really
// sequenceValue should he an ArrayList too.
sequenceValue = new long[100];
}




/**
* Add a new sequence
*/
public void add(NumberSequence seq) {
theSequences.add(seq);
}

/**
* Get the ith sequence
*/
public NumberSequence get(int i) {
return (NumberSequence)theSequences.get(i);
}

/**
* The number of sequences currently in the set
*/
public int numSequences() { return theSequences.size(); }

/**
* Show what all the sequences are
*/
public String toString() {
String result = "Number Sequences\n";
for (int i=0; i<numSequences(); i++)
result += this.get(i) + "\n";
return result;
}

/**
* Return an array of all the sequences
*/
public NumberSequence[] getAll( ) {
NumberSequence[] result = new NumberSequence[numSequences()];
for (int i=0; i<numSequences(); i++)
result[i] = this.get(i);
return result;
}

/**
* Throw away the sequences
*/
public void clear() {
theSequences.clear();
}

/**
* Delete the last sequence added, if any.
*/
public void deleteLast() {
if (numSequences() > 0) theSequences.remove(numSequences()-1);
}

/**
* Display the current values of the sequences on the screen.
*/
public void display(Graphics g) {
g.setColor(Color.black);
int textStart = minX + 10;
g.drawString("Step " + (n-1), textStart, minY );
if (numSequences() > 0) {
int spacePerSequence = (maxY - (minY+20)) / numSequences();
int y = minY + 20;
float scaleBy = this.scalingFactor();
for (int i=0; i< numSequences(); i++) {
g.drawString(get(i).toString(), textStart, y );
g.drawString(sequenceValue[i] + "", textStart, y+15);
g.setColor(Color.red);
g.fillRect(minX, y+20, (int)(sequenceValue[i]*scaleBy), 20);
g.setColor(Color.black);
y += spacePerSequence;
} // for
}// if
}

// Dummy implementation of TBSExtensions
public void doApplicationSpecificActions(String s, SimulationFrame frame) {}

public void doApplicationSpecificInitialisation(SimulationFrame f) { }


/**
* Return an empty - not null - SONS
*/
public ThingBeingSimulated emptyThing() {
return new SetOfNumberSequences();

}

/**
* Reset the step counter.
*/
public void resetCounter() {
n = 0;
}
// Utility method to figure out the scale for drawing bars, so that
// the largest bar takes between (width/2) and width.
// Multiply each value by this to get the length of the
// bar. Needs to be a float, because for large values it will
// be < 1.
protected float scalingFactor() {
int width = (maxX - minX) - 10;
long maxValue = 0;
for (int i=0; i<numSequences(); i++)
if (sequenceValue[i] > maxValue) maxValue = sequenceValue[i];
float scale = (float)1.0;
// At least one of the following loops will zero-trip.
// otherwise something has gone badly wrong.
while (maxValue > width) {
maxValue /=2;
scale /= 2;
}
if (maxValue > 0)
while (maxValue < (width/2)) {
maxValue *= 2;
scale *= 2;
}
return scale;
}
// The methods required by the ThingBeingSimulated interface.

/**
* Set the bounds within which the sequences will be displayed.
*/
public void setBounds(int minX, int minY, int maxX, int maxY) {
this.minX = minX;
this.minY = minY;
this.maxX = maxX;
this.maxY = maxY;
}
/** Perform a single step of simulation. Returns true unless
* a SequenceRangeException occurs.
*/
public void simstep() throws SimulationException {
try {
for (int i = 0; i < numSequences(); i++)
sequenceValue[i] = get(i).valueAt(n);
n++;
}
catch (SequenceRangeException e) {
throw new SimulationException(e.getMessage() );
}
}

/**
* Return an example SONS, for demo purposes.
*/
public ThingBeingSimulated typicalThing() {
SetOfNumberSequences s = new SetOfNumberSequences();
s.add(new ArithmeticProgression(1000,1000));
s.add(new Fibonacci());
return s;
}

/**
* Test program
*/
public static void main( String[] args) {
SetOfNumberSequences s = new SetOfNumberSequences();
s.add(new ArithmeticProgression(1000,1000));
s.add(new Fibonacci());
System.out.println(s);
}

} // SetOfNumberSequences
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
HHmmmmmmmmmmmmmmmmmm, ok. So simstep() shoudn't create any object, nor add anything to the list, that's what the add method is for, to add stuff from the simstep() method you would have to create objects and know whether you want a bus or a car or something else. So simstep() should be doing something else.
It seems to me that simstep() is meant to be called by another class SimulationFrame probably. This class seems to be the one that calls add(RoadVehicle) and simstep().
What's the details of simstep()? What should it do?
Maybe they want you to have an array of vehicles in the TrafficQueue class, fill it in using the add method, and then use simstep() to go through them.

The method simstep() in the SONS class gets a value from an ArrayList containing objects and puts that in an array. It uses a get method, and you have a get method in the TrafficQueue class, so it seems to be quite similar. The get method should get you something back depending on an index. For that change your get method from:



To:



So now this method could be used in simstep to go through an arraylist using a for loop, and at each loop getting a value and doind something with it. I m not sure what but if its really similar to the class you ve just shown me, it asks this object for some value and puts it in an array. So it might be very similar to this:



Sorry to hear about the cold, had one a few weeks ago. Keep us posted.

Hope it helps

Dani
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Dear All,

Thanks for all of the help and encouragement I have recieved.

I have managed to make some more progress with my programme and can now see the frame which will display my traffic queue. What I think I need to do now is within the simstep () method which performs a single step simulation I need to copy the values from my arraylist into an array using a get() method. I have therefore altered the constructor of the class so it can create both an arraylist and an array.

/** sample code to copy contents of arraylist into an array*/
for (int i=0; i<size(); i++)
arrayQueue[i] = queue.get(i);
count++;


my get() method should get the object stored at each element in the arraylist since the return is

queue.get(i);


The method to display the queue is defined in the TBS programmes and I have adapted it to display a message and eventually my TrafficQueue.

public void display (Graphics g) {
g.drawString("Happy New Year!", 200, 200);
for (int i=0; i<size(); i++){
g.drawString (get(i).toString(), 200, 200);
g.drawString (arrayQueue[i] + "", 200, 200);
}
}


This prints the first statement but not the following ones.

When the simulation is terminated I get a message

---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\java.exe" TrafficQueue
Array list
C
B
G
F

Look and feel set to com.sun.java.swing.plaf.windows.WindowsLookAndFeel
> Terminated with exit code 1.

I have used a print statement in main to print the arraylist but I am not sure how to do this for the array as this is definied in the simstep(). I think that the toString method that I have is OK as I only need to display a letter to represent each object. I have tried putting a print statement within simstep() method but then realised I did not know how to call the interal array.

Any ideas on any of this would me good.

Best wishes
Dianne
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Ok, i'm not sure i understood your questions correctly, could you paste the code of the relevant methods?
Are you wondering how to access an array withing the TrafficQueue class, or from another class?

To call an array that is withing the scope of a class, you can do this:



Dan
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
I have paste the major methods below. What I am not sure about is if this code is really copying the elements from the arraylist into the array. I think it should work but can not figure out why it is not and I do not have any way of testing it as I am not sure how to print out the elements in the array since they are in an internal method. In the past I have called methods within main by defining which instance I wanted them to work on.

queue1.add(bus1);
this calls the add() method to add the object bus2 to the arraylist queue1.

what I think the simstep() method does is setup a template to copy the elements from any arraylist to any array.

so I could possibly do

array1.simstep(queue1);
I could then test this by using a print statement
System.out.println(array1);

Which would test if the entire contents of queue1 have been copied into array1. Once I can convince myself of this I can then try to work out why it will not display to the frame.

Best wishes
Dianne






/** Constructs an empty Arraylist with the specified initial capacity
also an empty array capable of taking 20 RoadVehicle objects. */

public TrafficQueue(int size){
queue = new ArrayList<RoadVehicle> (size);
for (int i = 0; i < queue.size(); i ++)
queue.add(null);
count = 0;
arrayQueue = new RoadVehicle[20];
}
}


/** Returns the element at the specified position in this list.*/

public Object get(int i){
return queue.get(i);
}
}



/** Returns a string representation of the object.*/

public String toString(){
String result = "Array list\n";
for (int i=0; i<size(); i++)
result +=this.get(i) + "\n";
return result;
}

/** Methods from TBS Model. Set the bounds within which the TBS is displayed, 0...maxX by 0..maxY This is called before each call to display, so that if e.g. the window is resized, display() can use this information to size the representation of the TBS accordingly. */

public void setBounds(int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;
}

/** Methods from TBSModel Display the TBS on the screen. This is called whenever the display needs to be redrawn, including when the GUI is initialised and after every simstep(). */

public void display (Graphics g) {
g.drawString("Happy New Year!", 200, 200);
for (int i=0; i<size(); i++){
g.drawString (get(i).toString(), 200, 200);
g.drawString (arrayQueue[i] + "", 200, 200);
}
}

/** There is nothing in the DOC's of TBS to indicate what drawstring actually does. I have found this in the graphics DOC's and I think this is what is being used in this package.

public abstract void drawString(String str,
int x,
int y)Draws the text given by the specified string, using this graphics context's current font and color. The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system.

Parameters:
str - the string to be drawn.
x - the x coordinate.
y - the y coordinate.
public DrawString(java.lang.String str)*/

/** Initiates simulation of TBS interface. Copies the element
from the arrayList into an array which is internal to this method? */

public void simstep()throws SimulationException{
try{
for (int i=0; i<size(); i++)
arrayQueue[i] = queue.get(i);
count++;
}
catch (IndexOutOfBoundsException e){
throw new SimulationException (e.getMessage());
}
}


/** Main method */

public static void main (String [] args){

Car car1 = new Car ("C", "Ford", "Yellow");
Bus bus1 = new Bus ("B", "Blue", 30);
FireEnginefireEngine1=newFireEngine("F", "Standard", " red ");
GoodsVehicle goodsVehicle1 = new GoodsVehicle ("G", "green", " van ",4200);

TrafficQueue queue1 = new TrafficQueue (20);

try {queue1.add(car1);
queue1.add(bus1);
queue1.add(goodsVehicle1);
queue1.add(fireEngine1);
System.out.println(queue1);

}
catch(QueueFullException e){
System.out.println(e.getMessage()+ "queue1");
}

/** Test method to set up the frame with an empty queue
needs to be filled via the simstep() method*/

TrafficQueue q = new TrafficQueue (20);
SimulationFrame f = new SimulationFrame (500, 400, q);
f.setVisible(true);
}
}
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
I have just tried calling the simstep method in main BUT forgot once again that simstep() method does not take any parameter, so the code below is not allowed.

TrafficQueue queue1 = new TrafficQueue (20);
RoadVehicle[] array1 = new RoadVehicle[20];
array1.simstep(queue1);
System.out.println(array1);

I thought I had it all figured out, call the method to work on each instance of the class but no this is not the way the designers have written the TBS methods.

I have then tried array1.simstep();
but get the following error message

---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:149: cannot find symbol
symbol : method simstep()
location: class RoadVehicle[]
array1.simstep();
^
1 error
> Terminated with exit code 1.

I am left with a method which I am not sure how to use or worse still test, any suggestions?

Best wishes
Dianne Gerrelli
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Hmm, again not sure i'm quite getting you, but if you declare an array in the scope of the class, then that array is accessible by all the methods in your class (except main if i remember well, which is static). So you can declare an array as i showed you in my last post, and then have a getArrayElement(int index) where you return the array element by index, and then you could print it from the main method.
Otherwise you can just have a System.out.println(); in your simstep method to see what you're passing from the ArrayList into the array.



I hope i answered your question

Dani
Martin Mathis
Ranch Hand

Joined: Dec 20, 2004
Posts: 45
You are calling simstep on an array, not an instance of RoadVehicle. An array object doesn't have a simstep method defined, hence the compiler error.

If you want to call simstep on each element in an array use a loop.

I think you are making things a bit overly complicated, or maybe I'm not understanding things. When I think of a TrafficQueue, its actual job is to process the elements it contains. In this case, it means removal from the front. This is what your simulation needs to do, remove an element from the front, that's it.

You can add elements to the Queue, but thats not necessarily part of the simulation. That's why you have a seperate add method.

I haven't been following that much over the past few days, but I don't really see where you're headed with having both an ArrayList and an Array.

I think your TrafficQueue class can be broken down into something like the following.

add - adds elements to the end of the ArrayList
simstep - removes an element from the front of the ArrayList
display - do whatever you need to do on the GUI
reset - empties the ArrayList

I may have left out a few things, hope that helps... I'll try and check back throughout the day
Dianne Gerrelli
Ranch Hand

Joined: Dec 21, 2005
Posts: 45
Thanks for the help.

I think the worst part is that I do not really understand the exercise. I have tried to explain this to my "tutor" but he says he is not willing to debug my code!!!

I have an arraylist which I can add and remove from and get elements out of and it works as a queue so removes from front and adds to back. I need to be able to pass this to my simulation package and this is where I do not understand things as the main method simstep() takes no parameters. I therefore do not know how to pass it the queue or call this method

For example things the code below in main produce errors.

queue1.simstep();

---------- Capture Output ----------
> "C:\Program Files\Java\jdk1.5.0\bin\javac.exe" TrafficQueue.java
TrafficQueue.java:91: cannot find symbol
symbol : variable queue1
location: class TrafficQueue
queue1.simstep();
^
1 error
> Terminated with exit code 1.



I have been given a case study which is an example of something that almost works so thought I would try to adapt this.

It uses a get method to copy from an arrayList into an array within the simstep () method

/** Initiates simulation of TBS interface. */

public void simstep()throws SimulationException{
for (int i=0; i<size(); i++)
arrayQueue[i] = queue.get(i);

/** Trying to test if arraylist is being copied
System.out.println arrayQueue; but this does not work in here*/
count++;


/** If this loop is first in the method I get the exception message
printed in the simulation so this method is being called by something
but if I include it below the simulation says it has not started VERY IRRITATING**/

if (isEmpty())
throw new SimulationException
("SimulationException: haha can not simulate empty queue");
}


The display () method prints Happy New Year !!! within the simulation and the drawString method calls below are the same as in the case study but do not work

It is all very frustrating!!!

/** Display the TBS on the screen. This is called whenever the
display needs to be redrawn, including when the GUI is initialised
and after every simstep(). */

public void display (Graphics g) {
g.drawString("Happy New Year !!!", 100, 100);
for (int i=0; i<size(); i++){
g.drawString (get(i).toString(), 200, 200);
g.drawString (this.arrayQueue[i] + "", 200, 200);
}
}

I am sorry if this does not make any sense but as a beginner it is sometimes difficult to know what the main problems are with a programme. I am however very greatful to this message board as I may have given up days ago without the help I have recieved.

Best wishes
Dianne
Martin Mathis
Ranch Hand

Joined: Dec 20, 2004
Posts: 45
You shouldn't need to pass anything into the simstep function for it to do its job.

Lets assume that your class resembles the following (excuse the syntax and if I screw up on method names):



Lets ignore the GUI for now and assume the code that actually uses this is going to do look like the following:



Note, the above code is a as minimal as you can get, and rather generic. But I think it should give you a pretty good idea of my interpretation of your assignment. The requirements aren't really that clear, so I'm not 100% sure its what you need. Hope it helps though.
[ January 04, 2006: Message edited by: Martin Mathis ]
Dani Atrei
Ranch Hand

Joined: Feb 17, 2004
Posts: 73
Ok, i think Martin summed up things quite well. One thing though, i don't think the simstep() method is supposed to remove an object but to loop around the ArrayList if we're to follow one of the example classes of something your tutor said was quite similar. What the array is for though escapes my understanding, but i suspect it's to show that you can pass an object from a collection to an array.
I give the code of the simstep method of the similar class here:



On what concerns you trying to call simstep with queue1, as Martin says
You are calling simstep on an array, not an instance of RoadVehicle. An array object doesn't have a simstep method defined, hence the compiler error.


simstep() "belongs" to TrafficQueue, you can only call TraffiQueue methods with a variable referencing TraffiQueue. What you can do is fill the the ArrayList in TrafficQueue with RoadVehicle objects:



And then call the simstep method:



I ve got quite a lot going on now, i ll take a deeper look on the matter when i m more free.

Dan
Martin Mathis
Ranch Hand

Joined: Dec 20, 2004
Posts: 45
Just noticed that you had a little algorithim for the simstep, I assume your tutor or whoever gave you the assignment help you come up with it.

It says:

1.test if the queue is full
2. if it is remove the first vehicle
3. if the queue is not full, get a random vehicle from a list and add it to the end of the queue
4. then print a summary of the queue and the last vehicle added.


So if this is the case, it should transfer directly over to code almost directly. I guess the confusion would be in step 3.

It seems like here you would just need to randomly pick a type of RoadVehicle and add it to the queue. Maybe do something like the following:

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: programming to the interface