removeZero() method when creating linkedlist? - java

I am creating a LinkedList from scratch, in the form of a train. So I have a class called Domino which creates each node, and then I have the class Train, which includes the add, size, remove etc methods. My problem is:
removeZeros() method: I cannot have any parameters, but I must delete all the nodes with zeros in them. What my program does instead is find all the zeros in the list, and delete all the nodes up until there are no more zeros. The zeros were added in a client class.
here is my Train class:
public class Train{
private Domino engine;
private Domino caboose;
private int insertS;
public Train(){
engine = null;
caboose = engine;
}
/** WHERE IM HAVING TROUBLE
* removeZero() - remove any Dominos from the train that have one or more zero spots
* while maintaining the linked list structure.
*/
// method is now just getting the spot1 0 and printing that
public void removeZero(){
Domino current = engine;
Domino hold = caboose.next;
while (current != hold) {
if(current.spot1 == 0 ||current.spot2 == 0){
current = current.next;
engine = current;
System.out.println("b " + engine);
}else{
current = current.next;
}
}
public String toString(){
String ts = "{ empty }";
if (engine == null) {
return ts;
} else {
Domino hold = engine;
ts = "{ ";
while (hold != caboose) {
ts += hold + ", ";
hold = hold.next;
}
ts += hold + " }";
}
return ts;
}
/**
*
* add(spot1, spot2) - add a Domino to the end of the Train with the given spots
*/
public void add(int spot1, int spot2){
if (engine == null) {
engine = new Domino(spot1,spot2);
caboose = engine;
} else {
caboose.next = new Domino(spot1, spot2, null,caboose);
//tail.next.back = tail;
caboose = caboose.next;
}
}
}
/**
* reversePrint() - like toString, but provides a String that lists
* all of the Dominos that are in the Train in reverse order
*/
public String reversePrint () {
Domino hold = caboose;
String reverse = "{ empty }";
if (engine == null) {
System.out.println(reverse);
} else {
reverse = "{ ";
while (hold != engine){
reverse += hold + ", ";
hold = hold.back;
}
reverse += hold + " }";
}
return reverse;
}
/**
* size() - return the number of Dominos in the Train
*/
public int size(){
int count = 0;
Domino hold = engine;
while(hold != null){
hold = hold.next;
count++;
}
return count;
}
/** insert(spot1, spot2, next, back) - insert a Domino in the middle of
* the Train where spot2 is the same as the spot1 of the next Domino and spot1
* is the same as spot2 of the previous Domino.
* (private)
*/
private void insert(int spot1,int spot2){
if (!(insertS == search)) {
Domino hold = engine;
while (hold != caboose) {
if (hold.spot1 == search) {
Domino newDom = new Domino(spot1, spot2, null,caboose);
hold.next = newDom;
newDom.next.back = newDom;
hold = hold.next;
} else {
hold = hold.next;
}
}
if (hold.spot2 == search) {
add(spot1, spot2);
}
} else {
System.out.println(" ** Error Inserting these values will cause an infinite loop:");
System.out.println(" * * * " + insertS + " and " + search + " * * *");
}
}
/**
* build() - scans through the Train creating links, using insert(spot1, spot2), between
* existing Dominos where the second spot of the first Domino does not match the
* first spot of the second domino, no param
*/
public void build(){
insert(search, insertS);
}
}
here is my Domino class:
public class Domino{
public int spot1; // the leading half how many spots it has
public int spot2; // the trailing half how many spots it has
public Domino next; // a link to the next Domino (type)?
public Domino back; // a link to the previous Domino
private int zero;
/**
* Constructor
* Creates null Domino
*
*/
public Domino(){
this(0,0 , null, null);
}
/**
* Constructor
* a constructor for Domino with given spots
*/
public Domino( int spot1, int spot2){
this(spot1,spot2, null, null);
}
/**
* Constructor
* #param: all fields
* setting variables
*/
public Domino(int spot1, int spot2, Domino next, Domino back){
this.spot1 = spot1;
this.spot2 = spot2;
this.next = next;
this.back = back;
}
/**
* toString(): prints out single Domino
*
*/
public String toString(){
if(this == null){
return("[empty]");
}else{
return("[ " + spot1 + " | "+ spot2 + "]");
}
}
}
I've really been stuck on this for the past day or so and can't seem to figure it out. Any help would be great. If you need the client code please say so. Thanks!

In the case of encountering a zero domino, you assign engine to be the current domino. As engine is the head of the list, this is equivalent to deleting all the items preceding the one containing a zero. Deletion in linked list is usually accomplished by something like:
toDelete.back.next = toDelete.next;
toDelete.next.back = toDelete.back
where toDelete is a Domino object with a zero in this case. As no domino now has a reference to the toDelete domino, it is essentially deleted.

Related

Genric in Java Error --> class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Comparable;

Question
Create a class named KeepSmallArray that uses an array to implement the KeepSmallInterface. Use the program TestKeepSmall to test your implementation.
Basically i have to drop the two smallest scores from the assignement.
Key Points
KeepSmallArray object needs to be told at creation time how many grades (or whatever) it should keep track of.
Hints
helpful if you make the array one space larger than it "needs" to be. For example, if it's remembering 2 grades, make the array size 3.
You need to keep the elements of the array in order. Consider using the insert algorithm.
Error
Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Comparable; ([Ljava.lang.Object; and [Ljava.lang.Comparable; are in module java.base of loader 'bootstrap')
Attempted Solution
Tried error handling and changed some stuff around but that didnt help
however the problem seems to be in the constructor of the keepSmallArray class.
My code
TestKeepSmall
public class TestKeepSmall {
public static final int NUM_ASGNS = 10;
public static final Scanner kbd = new Scanner(System.in);
public static final Random r = new Random();
public static void main(String[] args) {
for (int numDrops = 2; numDrops < NUM_ASGNS / 2; ++numDrops) {
int numKeeps = NUM_ASGNS - numDrops;
Integer[] grades = new Integer[numKeeps];
int numKept = 0;
System.out.println("\n"
+ "Keeping the best " + numKeeps + " of " + NUM_ASGNS
+ " assignments.");
KeepSmallInterface<Integer> drops = new KeepSmallArray<>(numDrops);
// KeepSmallInterface<Integer> drops = new KeepSmallHeap<>(numDrops);
// test size/capacity/isEmpty
System.out.println(" --> starts with size 0: "
+ (drops.size() == 0 ? "PASS" : "FAIL ***"));
System.out.println(" --> starts with given capacity: "
+ (drops.capacity() == numDrops ? "PASS" : "FAIL ***"));
System.out.println(" --> starts empty: "
+ (drops.isEmpty() ? "PASS" : "FAIL ***"));
// toArray
Object[] dropObjects = drops.toArray();
System.out.println(" --> toArray() returns correct size: "
+ (dropObjects.length == drops.size()
? "PASS" : "FAIL ***"));
Comparable[] dropComps = drops.toArray(new Comparable[3]);
System.out.println(" --> toArray(T[]) returns correct size: "
+ (dropComps.length == 3
? "PASS" : "FAIL ***"));
boolean nulledOut = true;
for (int i = 0; i < dropComps.length; ++i) {
if (dropComps[i] != null) {
nulledOut = false;
}
}
System.out.println(" --> toArray(T[]) nulls unused elements: "
+ (nulledOut ? "PASS" : "FAIL ***"));
pause();
// test add
for (int i = 1; i <= NUM_ASGNS; ++i) {
// get a grade from the user
int grade = randomGrade();
System.out.printf("A%02d grade is %3d.%n", i, grade);
// see if it belongs on the drop list
Integer keeper = drops.add(grade);
// if not, add it to the kept grades array
if (keeper != null) {
grades[numKept] = keeper;
++numKept;
// test get
Integer newMaxDrop = drops.get(drops.size() - 1);
System.out.println(" --> \"bumped out\" largest value: "
+ (newMaxDrop <= keeper ? "PASS" : "FAIL ***"
+ "(dropped " + keeper + " instead of "
+ newMaxDrop + ")"));
}
}
pause();
// toArray
dropObjects = drops.toArray();
System.out.println(" --> toArray() returns correct size: "
+ (dropObjects.length == drops.size()
? "PASS" : "FAIL ***"));
System.out.println("\n"
+ "Your dropped grades are " + Arrays.toString(dropObjects)
+ "\nYour kept grades are " + Arrays.toString(grades));
// toArray(T[])
dropComps = drops.toArray(new Comparable[3]);
System.out.println(" --> toArray(T[]) returns correct size: "
+ (dropComps.length == Math.max(3, drops.size())
? "PASS" : "FAIL ***"));
boolean inOrder = true;
int upperBound = Math.min(dropComps.length, drops.size());
for (int j = 1; j < upperBound; ++j) {
if (dropComps[j - 1].compareTo(dropComps[j]) > 0) {
inOrder = false;
}
}
System.out.println(" --> toArray(T[]) returns ordered array: "
+ (inOrder ? "PASS" : "FAIL ***"));
if (upperBound < dropComps.length) {
nulledOut = true;
for (int i = upperBound; i < dropComps.length; ++i) {
if (dropComps[i] != null) {
nulledOut = false;
}
}
System.out.println(" --> toArray(T[]) nulls unused elements: "
+ (nulledOut ? "PASS" : "FAIL ***"));
}
// contains
Integer in = oneOf(dropObjects);
System.out.println(" --> contains " + in + ": "
+ (drops.contains(in) ? "PASS" : "FAIL ***"));
Integer out = oneNotOf(dropObjects);
System.out.println(" --> !contains " + out + ": "
+ (!drops.contains(out) ? "PASS" : "FAIL ***"));
pause();
}
}
private static void pause() {
System.out.print("\n...press enter...");
kbd.nextLine();
System.out.println();
}
private static int randomGrade() {
return Math.max(r.nextInt(101), r.nextInt(90));
}
private static Integer oneOf(Object[] dropComps) {
int len = dropComps.length;
int n = r.nextInt(len);
return (Integer)dropComps[n];
}
private static Integer oneNotOf(Object[] dropComps) {
int len = dropComps.length;
int result = 0;
boolean ok;
do {
ok = true;
result = r.nextInt(101);
for (int i = 0; ok && i < dropComps.length; ++i) {
if (dropComps[i].equals(result)) {
ok = false;
}
}
} while (!ok);
return result;
}
}
KeepSmallArray
public class KeepSmallArray<T extends Comparable<? super T>>
implements KeepSmallInterface<T> {
private T[] smallArray;
public KeepSmallArray(int len) {
if(len <= 0) {
throw new NullPointerException();
}
smallArray = (T[]) new Object[len + 1];
}
#Override
public int size() {
int count = 0;
for (T item : smallArray) {
if (item != null) {
count++;
} else {
break;
}
}
return count;
}
#Override
public int capacity() {
return smallArray.length;
}
#Override
public boolean isEmpty() {
return size() == 0;
}
#Override
public void clear() {
try{
smallArray = (T[]) new Object[smallArray.length];
}
catch(Exception e){
}
}
#Override
public boolean contains(Object obj) {
for (T item : smallArray) {
if (obj.equals(item)) {
return true;
}
}
return false;
}
#Override
public Object[] toArray() {
return toArray(smallArray);
}
#Override
public Object[] toArray(Object[] array) {
if (array == null) {
throw new NullPointerException("given array is not initialized");
}
return array;
}
#Override
public T add(T newElement) {
if (newElement == null) {
throw new NullPointerException("null cannot be added");
}
return null;
}
#Override
public T get(int index) {
if (index < 0 || index > size() - 1) {
throw new IllegalArgumentException("index out of range");
}
return smallArray[index];
}
}
Keep Interface
/**
* A collection of "small" elements, sorted from smallest to largest.
* The collection contains a limited number of elements (its capacity).
* The client may request that a new element be added, but that element
* will only be added if there is room for it <em>or</em> if it is smaller
* than one of the elements currently stored in this container. In the
* latter case, the largest element in the container will be "bumped out"
* to make room for the new one.
* <p>
* Such a container may be used to keep track of assignment grades to be
* dropped from an average (for example, to track the two smallest of ten
* assignment grades). Alternatively, an appropriately programmed class
* could instead track the eight highest grades from ten (tho' such a class
* might better be called a "KeepBig" container).
*
*
*/
public interface KeepSmallInterface<T extends Comparable<? super T>> {
/**
* The number of elements currently in this container.
*
* #return the number of elements in this container.
*/
public int size();
/**
* The maximum number of elements this container can hold.
*
* #return the number of elements this container can hold.
*/
public int capacity();
/**
* Whether this bag is empty.
*
* #return true if this container has no elements in it; false otherwise.
*/
public boolean isEmpty();
/**
* Remove all the elements from this container.
*/
public void clear();
/**
* Consider the given element for addition to this container.
* If there is space available in this container, then given element
* will be added and <code>null</code> returned. Otherwise the
* largest of the current elements and the given element will be
* "bumped out" and returned. (Note that the given element may be
* the one "bumped out".)
*
* #param newElement the element to add.
* #return the element "bumped out" of this container;
* OR null if no element was "bumped out".
* #throws NullPointerException if <code>newElement</code> is
* <code>null</code>
*/
public T add(T newElement);
/**
* The smallest-but-<tt>i</tt> element in this container. For example,
* <code>get(0)</code> returns the smallest element in this container,
* while <code>get(2)</code> returns the third smallest element
* (<i>i.e.</i> the one with exactly two elements before it in the sorted
* order).
*
* #param index the number of smaller elements than the one requested.
* #return the smallest-but-<tt>index</tt> element in this container;
* OR null if there is none.
* #throws IllegalArgumentException if <tt>index</tt> is not in the range
* <code>0..size()-1</code>
*/
public T get(int index);
/**
* Whether the container contains the given element.
*
* #param obj the element to test for.
* #return true if it's present; false otherwise.
*/
public boolean contains(Object obj);
/**
* An array containing all the elements of this container, in order from
* smallest to largest.
*
* #return a sorted array with all this container's elements.
*/
public Object[] toArray();
/**
* Returns an array containing all of the elements in this container sorted
* from smallest to largest; the runtime type of the returned array is that
* of the given array. If the list fits in the given array, it is returned
* therein. Otherwise, a new array is allocated with the runtime type of
* the specified array and just large enuf to hold all this container's
* elements.
*
* #param <E> The base type of the passed-in array.
* #param array the array to place the elements in.
* #return a sorted array with all this container's elements.
* #throws ArrayStoreException - if the runtime type of the specified
* array is not a supertype of the runtime type of every element in this
* container.
* #throws NullPointerException if the specified array is null.
*/
public <E> E[] toArray(E[] array);
}
So you can't use an array of Object since you are storing Comparable. Instead, you need to use an array of Comparable.
smallArray = (T[]) new Object[len + 1];
should be
smallArray = (T[]) new Comparable[len + 1];

java program is printing objects in the wrong order

I'm trying to write a class called RailwayStation that will print an array of train (using two different classes I wrote called TIME1and Train. My problem is that I can't understand why the output is arranged in the wrong order.
I assume the problem is in the method inside the class called addTrain, which supposed to add a train trip if there exists an empty cell in the array, and if the trip that wishes to be added does not exists already in the array. another method I used (and might be the problem) is called removeTrain, which receives a parameter of a train trip and removes that from the array. My methods addTrain, removerTrain, and toStringis as follows:
public class RailwayStation {
// declrations of final variables
private final int MAX_TRAINS = 100;
private final int MIN_VAL = 0;
// declrations of instant variables
private Train[] _station;
private int _noOfTrs;
/**
* Empty construter which initialize the instant variables of the class such that the trips array will be in a maximal size
*/
public RailwayStation() {
_station = new Train[MAX_TRAINS];
_noOfTrs = MIN_VAL;
}
/**
* adds a train trip to the trips array
*
* #param f the train trip
* #Returns true if a train trip has been added to the trips array
*/
public boolean addTrain(Train f) {
int i, j;
// boolean found = false;
if (isTrainOnSomeStation(f)) {
return false;
}
else {
for (j = MIN_VAL; j < _station.length; j++) {
if (_station[j] == null) {
_station[j] = f;
_noOfTrs++;
return true;
}
}
return false;
}
}
// a private method that checks if #param f is null
private boolean isTrainOnSomeStation(Train f) {
if (f == null) {
return false;
}
for (int i = MIN_VAL; i < _station.length; i++) {
if (_station[i] != null && _station[i].equals(f)) {
return true;
}
}
return false;
}
/**
* removes a trip from the trips array
* #param f the train trip
* #returns true if the train trip has been removed
*/
public boolean removeTrain(Train f) {
int i, j;
boolean found = false;
for (j = MIN_VAL; j < _station.length && !found; j++) {
if (_station[j] != null) {
for (i = MIN_VAL; i < _noOfTrs && !found; i++)
if (_station[i].equals(f)) {
_station[i] = _station[_noOfTrs];
_station[_noOfTrs] = null;
found = true;
_noOfTrs--;
}
}
}
return found;
}
/** Returns a string which describes all train in the array as apperas in the arrray
* #Returns a string of trains as appears in the arrat
*/
public String toString(){
String str = "The trains today are:" +"\n";
if(_noOfTrs == MIN_VAL){
return "There are no trains today.";
}
else {
String capacity = "";
for (int i = 0; i < _station.length; i++) {
if (_station[i] != null) {
if (_station[i].isFull() == true) {
capacity = "Train is full";
}
else {
capacity = "Train is not full";
}
str += _station[i].toString() + "\n";
}
}
}
return str;
}
}
In order to call the method addTrain I'll be writing:
//Check constructor
RailwayStation rs = new RailwayStation();
//AddTrain
Train f1 = new Train("Haifa",12,0,210,250,250,55);
Train f2 = new Train("Jerusalem",10,50,210,250,250,40);
rs.addTrain(f1);
rs.addTrain(f2);
System.out.println(rs);
//RemoveTrain
rs.removeTrain(f1);
System.out.println(rs);
//First Train to Destination
Train f3 = new Train("Tel-Aviv",11,35,180,100,200,35);
rs.addTrain(f3);
Train f3a = new Train("Tel-Aviv",7,15,180,200,200,35);
rs.addTrain(f3a);
I'm expecting to get the output:
The trains today are:
Train to Jerusalem departs at 10:50. Train is full.
Train to Tel-Aviv departs at 11:35. Train is not full.
Train to Tel-Aviv departs at 07:15. Train is full.
but what I get is:
The trains today are:
Train to Tel-Aviv departs at 11:35. Train is not full.
Train to Jerusalem departs at 10:50. Train is full.
Train to Tel-Aviv departs at 07:15. Train is full.
I've tried to use the debugger in order to understand in what part the order gets wrong, but I can't locate the problem.
When you add the first trains your array is like so:
Train[0] = Haifa...
Train[1] = Jerusalem..
Train[2] = null
Train[3] = null
...
Then you remove Haifa:
Train[0] = null
Train[1] = Jerusalem..
Train[2] = null
Train[3] = null
...
Then you add the other trains:
Train[0] = Tel Aviv..
Train[1] = Jerusalem..
Train[2] = Tel Aviv..
Train[3] = null
...
Does that explain it?
The data structure you're trying to build here is a Stack - but the good news is that java already has one, so no need to do what you are trying to do:
Stack<Train> trains = new Stack<>();
Train f1 = new Train("Haifa",12,0,210,250,250,55);
Train f2 = new Train("Jerusalem",10,50,210,250,250,40);
trains.push(f1);
trains.push(f2);
//RemoveTrain
trains.remove(f1);
//First Train to Destination
Train f3 = new Train("Tel-Aviv",11,35,180,100,200,35);
trains.push(f3);
Train f3a = new Train("Tel-Aviv",7,15,180,200,200,35);
trains.push(f3a);
String str = "The trains today are:" +"\n";
for(Train train: trains) {
str = str + train + "\n";
}
System.out.println(str);

Java Homework Assignment Linked List

Thank you for everyone who got me on my feet. However, My cutSplice method is inefficient. I need to be able to modify it easy so that i can do the reverse method.
developing a single Java class (LinkedDnaStrand) that uses a linked list of nodes to represent a strand of DNA that supports splicing. Each node in the list will contain a string of one or more nucleotides (A, C, G, or T). The class will be responsible for operations such as append() and cutSplice(), which model real-world restriction enzyme processing.
EX. tt will be replaced with cat. (Better LinkedDnaStrandTester)
package dnasplicing;
public class DnaSequenceNode {
public String dnaSequence;
public DnaSequenceNode previous;
public DnaSequenceNode next;
public DnaSequenceNode(String initialDnaSequence) {
dnaSequence = initialDnaSequence;
}
}
package dnasplicing;
public class LinkedDnaStrand implements DnaStrand {
int nodeCount = 0;
int appendCount = 0;
long nucleotideCount = 0;
String sequenceString;
DnaSequenceNode cursor, head, tail;
public LinkedDnaStrand(String dnaSequence) {
DnaSequenceNode newNode = new DnaSequenceNode(dnaSequence);
head = newNode;
cursor = head;
tail = head;
head.previous = null;
tail.previous = null;
sequenceString = dnaSequence;
nodeCount++;
}
public String toString() {
String result = "";
DnaSequenceNode n = head;
while (n != null) {
result += n.dnaSequence;
n = n.next;
}
return result;
}
#Override
public long getNucleotideCount() {
nucleotideCount = sequenceString.length();
return nucleotideCount;
}
#Override
public void append(String dnaSequence) {
if (dnaSequence != null && dnaSequence.length() > 0) {
tail.next = new DnaSequenceNode(dnaSequence);
tail.next.previous = tail;
tail = tail.next;
sequenceString += dnaSequence;
appendCount++;
nodeCount++;
}
}
#Override
public DnaStrand cutSplice(String enzyme, String splicee) {
boolean frontSplice = false;
boolean backSplice = false;
if (sequenceString.startsWith(enzyme)) {
frontSplice = true;
}
if (sequenceString.endsWith(enzyme)) {
backSplice = true;
}
String[] dnaParts = sequenceString.split(enzyme);
LinkedDnaStrand newLinkedStrand = null;
if (frontSplice == true) {
newLinkedStrand = new LinkedDnaStrand(splicee);
// newLinkedStrand.append(dnaParts[0]);
for (int i = 1; i < dnaParts.length; i++) {
newLinkedStrand.append(dnaParts[i]);
if (i < dnaParts.length - 1) {
newLinkedStrand.append(splicee);
}
}
} else {
newLinkedStrand = new LinkedDnaStrand(dnaParts[0]);
for (int index = 1; index < dnaParts.length; index++) {
newLinkedStrand.append(splicee);
newLinkedStrand.append(dnaParts[index]);
}
}
if (backSplice == true) {
newLinkedStrand.append(splicee);
}
// sequenceString = newLinkedStrand.toString();
return newLinkedStrand;
}
#Override
public DnaStrand createReversedDnaStrand() {
// TODO Auto-generated method stub
return null;
}
#Override
public int getAppendCount() {
// TODO Auto-generated method stub
return appendCount;
}
#Override
public DnaSequenceNode getFirstNode() {
return head;
}
#Override
public int getNodeCount() {
return nodeCount;
}
}
package dnasplicing;
public interface DnaStrand {
/**
* NOTE: Your LinkedDnaStrand class must have a constructor that takes one parameter: String dnaSequence. When the
* constructor completes, your linked list should have just one node, and it should contain the passed-in
* dnaSequence. For example, if the following line of code was executed:
*
* LinkedDnaStrand strand = new LinkedDnaStrand("GATTACA");
*
* Then strand's linked list should look something like (previous pointers not shown):
*
* first -> "GATTACA" -> null
*
* The first line of this constructor should look like:
*
* public LinkedDnaStrand(String dnaSequence) {
*/
/**
* #return The entire DNA sequence represented by this DnaStrand.
*/
public String toString();
/**
* Returns the number of nucleotides in this strand.
*
* #return the number of base-pairs in this strand
*/
public long getNucleotideCount();
/**
* Appends the given dnaSequence on to the end of this DnaStrand. appendCount is incremented. Note: If this
* DnaStrand is empty, append() should just do the same thing as the constructor. In this special case, appendCount
* is not incremented.
*
* #param dnaSequence
* is the DNA string to append
*/
public void append(String dnaSequence);
/**
* This method creates a <bold>new</bold> DnaStrand that is a clone of the current DnaStrand, but with every
* instance of enzyme replaced by splicee. For example, if the LinkedDnaStrand is instantiated with "TTGATCC", and
* cutSplice("GAT", "TTAAGG") is called, then the linked list should become something like (previous pointers not
* shown):
*
* first -> "TT" -> "TTAAGG" -> "CC" -> null
*
* <b>NOTE</b>: This method will only be called when the linke list has just one node, and it will only be called
* once for a DnaStrand. This means that you do not need to worry about searching for enzyme matches across node
* boundaries.
*
* #param enzyme
* is the DNA sequence to search for in this DnaStrand.
*
* #param splicee
* is the DNA sequence to append in place of the enzyme in the returned DnaStrand
*
* #return A <bold>new</bold> strand leaving the original strand unchanged.
*/
public DnaStrand cutSplice(String enzyme, String splicee);
/**
* Returns a <bold>new</bold> DnaStrand that is the reverse of this strand, e.g., if this DnaStrand contains "CGAT",
* then the returned DnaStrand should contain "TAGC".
*
* #return A <bold>new</bold> strand containing a reversed DNA sequence.
*/
public DnaStrand createReversedDnaStrand();
/**
*
* #return The number of times that the DnaStrand has been appended via a call to append() or during the cutSplice()
* operation. Note that the very first time that a DnaStrand is given a DNA sequence is not to be counted as
* an append.
*/
public int getAppendCount();
/**
* This is a utility method that allows the outside world direct access to the nodes in the linked list.
*
* #return The first DnaSequenceNode in the linked list of nodes.
*/
public DnaSequenceNode getFirstNode();
/**
* This is a utility method that allows the outside world to determine the number of nodes in the linked list.
*
* #return
*/
public int getNodeCount();
}
package sbccunittest;
import static java.lang.Math.*;
import static java.lang.System.*;
import static org.apache.commons.lang3.StringUtils.*;
import static org.junit.Assert.*;
import java.io.*;
import org.apache.commons.lang3.*;
import org.junit.*;
import dnasplicing.*;
// Updated 25-Feb-2016 at 6:10pm
public class LinkedDnaStrandTester {
static String ecoliSmall = "AGCTTTTCATTAGCCCGCAGGCAGCCCCACACCCGCCGCCTCCTGCACCGAGAGAGATGGAATAAAGCCCTTGAACCAGC";
static String ecor1 = "GAATTC"; // restriction enzyme
public static int totalScore = 0;
public static int extraCredit = 0;
public static InputStream defaultSystemIn;
public static PrintStream defaultSystemOut;
public static PrintStream defaultSystemErr;
public static String newLine = System.getProperty("line.separator");
public void testCutSplice() {
String enzyme = "GAT";
String splicee = "TTAAGG";
String[] strands = { "TTGATCC", "TCGATCTGATTTCCGATCC", "GATCTGATCTGAT" };
String[][] recombinants = { { "TT", "TTAAGG", "CC" },
{ "TC", "TTAAGG", "CT", "TTAAGG", "TTCC", "TTAAGG", "CC" },
{ "TTAAGG", "CT", "TTAAGG", "CT", "TTAAGG" } };
for (int ndx = 0; ndx < strands.length; ndx++) {
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(strands[ndx]);
DnaStrand newlinkedStrand = linkedStrand.cutSplice(enzyme, splicee);
assertEquals("cutSplice(" + enzyme + ", " + splicee + ") failed at ndx = " + ndx, join(recombinants[ndx]),
newlinkedStrand.toString());
assertEquals("Append counts didn't match for ndx = " + ndx, recombinants[ndx].length - 1,
newlinkedStrand.getAppendCount());
// Verify that each node contains the correct DNA sequence
DnaSequenceNode node = newlinkedStrand.getFirstNode();
for (int nodeNdx = 0; nodeNdx < recombinants.length; nodeNdx++) {
assertNotNull("For strand " + ndx + ", there is no node at position " + nodeNdx, node);
assertEquals("For strand " + ndx + ", the sequences don't match at position " + nodeNdx,
recombinants[ndx][nodeNdx], node.dnaSequence);
node = node.next;
}
}
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice of (part of) the E Coli sequence using the ECoR1
* restriction enzyme and insulin as a splicee.
*/
#Test
public void testSpliceInsulinIntoEcoli() {
for (int testNumber = 1; testNumber <= 5; testNumber++) {
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the
// first third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
DnaStrand newL = linkedStrand.cutSplice(ecor1, insulin);
DnaStrand newS = simpleStrand.cutSplice(ecor1, insulin);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
assertEquals(newS.getAppendCount(), newL.getNodeCount() - 1);
// Verify that the nodes exist
DnaSequenceNode node = newL.getFirstNode();
for (int ndx = 0; ndx < newL.getNodeCount(); ndx++) {
assertNotNull("There is no node at position " + ndx, node);
node = node.next;
}
}
totalScore += 10;
}
/**
* Verifies that LinkedDnaStrand can model a cut and splice efficiently.
*/
#Test
public void testSplicingTime() {
// First verify that the LinkedDnaStrand cutSplice works
int startNdx = (int) (random() * 0.33 * ecoliSmall.length()); // Somewhere in the first
// third
int endNdx = ecoliSmall.length() - 1 - (int) (random() * 0.33 * ecoliSmall.length());
String ecoliPart = ecoliSmall.substring(startNdx, endNdx);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(ecoliPart);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(ecoliPart);
String splicee = createRandomDnaSequence(1024 * 1024, 1024 * 1024);
DnaStrand newL = linkedStrand.cutSplice(ecor1, splicee);
DnaStrand newS = simpleStrand.cutSplice(ecor1, splicee);
assertEquals(newS.toString(), newL.toString());
assertEquals(newS.getAppendCount(), newL.getAppendCount());
// Now verify that it can cut and splice N times in less than T seconds
int numSplicings = 200;
double maxTime = 2.0;
double start = nanoTime();
for (int i = 0; i < numSplicings; i++)
newL = linkedStrand.cutSplice(ecor1, splicee);
double end = nanoTime();
double time = ((end - start) / 1e9);
// out.println("Time = " + time);
assertTrue("Time limit of " + maxTime + " seconds exceeded. Time to splice " + numSplicings + " times was "
+ time + " seconds.", time <= maxTime);
totalScore += 5;
}
/**
* Verifies that LinkedDnaStrand can create a new, reversed LinkedDnaStrand.
*/
#Test
public void testReverse() {
String dnaSequence = createRandomDnaSequence(50, 100);
String dnaToAppend = createRandomDnaSequence(5, 10);
int numTimesToAppend = (int) (random() * 10);
LinkedDnaStrand linkedStrand = new LinkedDnaStrand(dnaSequence);
SimpleDnaStrand simpleStrand = new SimpleDnaStrand(dnaSequence);
for (int ndx = 0; ndx < numTimesToAppend; ndx++) {
linkedStrand.append(dnaToAppend);
simpleStrand.append(dnaToAppend);
}
assertEquals(simpleStrand.toString(), linkedStrand.toString());
assertEquals(numTimesToAppend + 1, linkedStrand.getNodeCount());
LinkedDnaStrand rl = (LinkedDnaStrand) linkedStrand.createReversedDnaStrand();
// Verify that the original linked strand wasn't changed
DnaSequenceNode node = linkedStrand.getFirstNode();
int nodeNdx = 0;
while (node != null) {
assertEquals("Sequences don't match at node index " + nodeNdx, nodeNdx == 0 ? dnaSequence : dnaToAppend,
node.dnaSequence);
node = node.next;
nodeNdx++;
}
// Verify that the new strand string is reversed
assertEquals(simpleStrand.createReversedDnaStrand().toString(), rl.toString());
totalScore += 10;
// If the new strand has a reverse order of nodes and sequences within each node, give extra
// credit
int numNodes = linkedStrand.getNodeCount();
if (numNodes == rl.getNodeCount()) {
// Build array of reversed dna strings from original LinkedDnaStrand. Start at end of
// array and move toward
// start
node = linkedStrand.getFirstNode();
String[] reversedDnaSequences = new String[linkedStrand.getNodeCount()];
nodeNdx = numNodes - 1;
while (node != null) {
reversedDnaSequences[nodeNdx] = reverse(node.dnaSequence);
node = node.next;
nodeNdx--;
}
// Verify that the reversed list's nodes contain the same data as in the array
node = rl.getFirstNode();
nodeNdx = 0;
while (node != null) {
if (!node.dnaSequence.equals(reversedDnaSequences[nodeNdx]))
break;
node = node.next;
nodeNdx++;
}
if (nodeNdx == linkedStrand.getNodeCount())
extraCredit += 5;
}
}
private String[] createRandomDnaSequences(int numDnaSequences, int minLength, int maxLength) {
String[] dnaSequences = new String[numDnaSequences];
for (int ndx = 0; ndx < numDnaSequences; ndx++)
dnaSequences[ndx] = createRandomDnaSequence(minLength, maxLength);
return dnaSequences;
}
private String createRandomDnaSequence(int minLength, int maxLength) {
return RandomStringUtils.random((int) (random() * (maxLength - minLength) + minLength), "ACGT");
}
#BeforeClass
public static void beforeTesting() throws Exception {
totalScore = 0;
extraCredit = 0;
}
#AfterClass
public static void afterTesting() {
out.println("Estimated score (w/o late penalties, etc.) = " + totalScore);
out.println("Estimated extra credit (assuming on time submission) = " + extraCredit);
}
#Before
public void setUp() throws Exception {
defaultSystemIn = System.in;
defaultSystemOut = System.out;
defaultSystemErr = System.err;
}
#After
public void tearDown() throws Exception {
System.setIn(defaultSystemIn);
System.setOut(defaultSystemOut);
System.setErr(defaultSystemErr);
}
public void sendToStdinOfTestee(String message) {
System.setIn(new ByteArrayInputStream(message.getBytes()));
}
}
So I don't have some of the classes like the node class you are using so I cannot write the actual code but i will give you some pseudo code.
public String toString(){
String result = "";
Node n = start;
while(n != null){
string += n.data;
}
return result;
}
public long getNucleotideCount() {
long result = 0;
Node n = start;
while(n != null){
result += n.data.length();
}
return result;
}
public void append(String dnaSequence) {
end.next = new Node(dnaSequence);
end = end.next;
appendCount++;
}
public DnaStrand cutSplice(String enzyme, String splice) {
// For this I think it would be best to assemble into string then use replace
Node n = start;
String result = "";
while(n != null){
result += n.data;
}
result = result.replace(enzyme, splice)
return new DnaStrand(result);
}
The reverse method would be similar to cutSplice. Assemble to string, manipulate, then return new strand. If you need more help LMK.

Issues with toString and Inheritance [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have I am having trouble figuring out an issue I have with a toString method. toString () must be changed so that it prints all the relevant information about the Player (and collection of
Items). Subclasses should overwrite the superclass toString (), but still use the toString ()
from the super class implementation when this reduces code duplication.
How do I go about doing this?
Player class:
import java.util.HashMap;
public class Player extends Character {
private String name;
private String type;
public static HashMap<String, Item> backpack;
private int maxCarryingCapacity;
/**Constructor
* Creates a player with health 100, an empty backpack
* and max carrying capacity 100
*
* #param nick the players name
* #param type the players type
* #param minDamage players minimum damage
* #param maxDamage players maximum damage
*/
public Player(String name, String type, int minDamage, int maxDamage) {
super(name, minDamage, maxDamage);
setName(name);
setType(type);
health = 100;
gold = 100;
backpack = new HashMap<String, Item>();
maxCarryingCapacity = 100;
setMinDamage(minDamage);
setMaxDamage(maxDamage);
}
/**
* Use an item in backpack
* #param itemName
* #return true if item is used, and false
* if there's no item by that name in the backpack
*/
public boolean useItem(String itemName) {
Item item = findItem(itemName);
if(item != null) {
System.out.println(name + " " + item.getAction() + " " + item.getName());
return true;
} else {
return false;
}
}
public boolean equipItem(String itemToEquip) {
Item item = findItem(itemToEquip);
if (item != null) {
this.minDamage = this.minDamage + item.getBonus();
return true;
} else {
return false;
}
}
/**
* Adds item to players inventory. An
* item can only be bought if the total weight does not
* exceed the players carrying capacity
* #param item
* #return true if the item is bought
*/
public boolean addItem(Item item) {
int totalWeight = totalWeight() + item.getWeight();
if(totalWeight <= maxCarryingCapacity){
backpack.put(item.getName(), item);
return true;
} else {
return false;
}
}
/**
* Find item in backpack
*
* #param name of item
* #return item, or null if item is not int the backpack
*/
public Item findItem(String itemName) {
return backpack.get(itemName);
}
/**
* Removes item from player's backpack and
* add item value to player's gold
*
* #param name of item to sell
* #return true if successful
*/
public boolean sellItem(String itemToSell) {
Item item = findItem(itemToSell);
if(item != null) {
gold += item.getValue();
backpack.remove(item.getName());
return true;
} else {
return false;
}
}
/**
* #return true if the player is alive
*/
public boolean isAlive() {
if(health > 0 && health <= 100) {
return true;
} else return false;
}
/**
* #return a string with player information
*/
#Override
public String toString() {
String string = "Name: " + name + " Type: " + type + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return string;
}
/**
* #return the players type
*/
public String getType() {
return type;
}
/**Sets the players type
* Valid types: Mage, Ranger, Warrior, Rogue
* #param newType
*/
public void setType(String newType) {
newType = newType.toLowerCase().trim();
if(newType.equals("mage") || newType.equals("ranger") || newType.equals("warrior") || newType.equals("rogue")){
this.type = newType;
} else {
this.type = "Unspecified";
}
}
/**
* #param item
* #return current carrying weight
*/
private int totalWeight() {
int tempWeight = 0;
for(Item itemInBackpack : backpack.values()) {
tempWeight += itemInBackpack.getWeight();
}
return tempWeight;
}
public int attack(Monster currentEnemy) {
int damage = Utils.random(minDamage, maxDamage+1);
currentEnemy.changeHealth(-damage);
return damage;
}
}
The Character superclass (abstract class):
abstract class Character
{
public String name;
public static int health;
public int gold;
public int minDamage;
public int maxDamage;
public Character(String name, int minDamage, int maxDamage) {
setName(name);
health = 100;
gold = 100;
setMinDamage(minDamage);
setMaxDamage(maxDamage);
}
public Character () {
}
/**
* Changes the character health
* The health can not be less the 0 or "less than or euqal to" 100.
* #param healthPoints
*/
public void changeHealth(int healthPoints) {
int temp = health + healthPoints;
if(temp > 100) {
health = 100;
} else if (temp <= 0) {
health = 0;
} else {
health = temp;
}
}
/**
* #return true if the character is alive
*/
public boolean isDead() {
if(health > 0 && health <= 100) {
return false;
} else return true;
}
/**
* #return the characters name
*/
public String getName() {
return name;
}
/**Set to Unspecified if the string is empty
* #param name
*/
public void setName(String name) {
this.name = Utils.checkString(name);
}
/**
* #return the characters health
*/
public static int getHealth() {
return health;
}
/**
* Get minimum damage
* #return minimum damage
*/
public int getMinDamage() {
return minDamage;
}
/**
* Set minimum damage, if minDamage >= 5, minDamage is otherwise set to 5
* #param minimum Damage
*/
public void setMinDamage(int minDamage) {
this.minDamage = minDamage >= 5 ? minDamage : 5;
}
/**
* Get maximum damage
* #return maximum damage
*/
public int getMaxDamage() {
return maxDamage;
}
/**
* Set maximum damage, if maxDamage <= minDamage, maxDamage is set to minDamage +5
* #param maximum damage
*/
public void setMaxDamage(int maxDamage) {
this.maxDamage = maxDamage <= minDamage ? minDamage+5 : maxDamage;
}
/**
* Get money
* #return amount of money
*/
public int getGold() {
return gold;
}
/**
* Set money
* #param amount of money
*/
public void setGold(int gold) {
this.gold = Utils.checkNegativeInt(gold);
}
}
In general, given two classes, A and B and if class B extends A then B has all of the properties of A plus some of its own. Therefore, when you implement B's toString() method, you should do this:
#Override
public String toString() {
String newStuff = // description of the new variables
return super.toString() + newStuff;
// Now describe the elements of B that aren't included in A
}
However, your implementation doesn't give a basic toString() method for Character so calling super.toString() is equivalent to calling Object.toString(). Therefore you should first implement toString for your Character abstract class.
for example, you could do:
public String toString() {
return "Name: " + name + "\nHealth: " ... all the attributes
}
There is a lot of redundancy in your code though. First of all, both your Character class and your Player class have the same name variable, which goes against the point of inheritance. In fact, you never even use Player's name variable.
also, there is no point in creating getter/setter methods in Character if all the variables are declared public anyways. It is better to make them private and use getter/setters though.
Your abstract superclass has name and health, but not type or backpack. (I just noticed, thanks to user2573153's answer, that you also have name in your Player class; I don't think you want that.)
I think the first thing you want to do is to answer this question: Suppose you create a new subclass, and you don't override toString(), and then an object gets printed out. What would you want to see printed out?
Maybe you want the name and health printed out. So you can declare this in your abstract Character class (which I think shouldn't be called Character because java.lang already has a Character):
#Override
public String toString() {
String string = "Name: " + name + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
return string;
}
Then, if you wanted toString() in Player or Monster to add something to the end of that, it would be pretty easy:
#Override
public String toString() {
String string = super.toString(); // here's where you call the superclass version
string += "\n Type: " + type;
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return string;
}
In your actual code, however, you want the Type information inserted in the middle of the string that the superclass toString() would return. That makes things tougher. I can think of two ways to handle it. One would be to use some string manipulation methods to search for \n and insert the "Type" string in there. But I think it's better to split the string into two methods. You can put these in your Character class:
protected String nameString() {
return "Name: " + name;
}
protected String healthString() {
if(isAlive()) {
return "Is alive with health: " + health;
} else {
return "Is dead.";
}
}
Now, your toString() in Character might look like
#Override
public String toString() {
return nameString() + "\n" + healthString();
}
and in Player:
#Override
public String toString() {
return nameString() + " Type: " + type + "\n" + healthString();
}
and you still get to avoid duplicated code. (You don't need to say super.nameString() because your subclass will automatically inherit it and you don't plan to override it.)
Superclass methods aren't automatically called. When you override toString() in Player and you call toString() on an instance of Player the only code that gets run is Player's toString().
If you want to include the toString() of Character in your toString() of Player you need to make that explicit by calling super.toString() in Player's toString().
Your Player implementation of toString() could be amended to include my recommendation as follows:
/**
* #return a string with player information
*/
#Override
public String toString() {
String string = "Name: " + name + " Type: " + type + "\n";
if(isAlive()) {
string += "Is alive with health: " + health;
} else {
string += "Is dead.";
}
string += "\n"+ name + "'s backpack contains the following items: \n";
for(Item item : backpack.values()) {
string += item;
}
return super.toString() + string;
}
The salient part of this is changing:
return string;
To:
return super.toString() + string;

Error in my Queue simulator

The program simulates a customer service operation in places, e.g., call center, bank, store, airport, with customers being served by tellers. The customers arrive at random time and wait in a line until a teller is available to serve them. The waiting line is implemented with queue data structure. However im getting two minor errors 1.) my enqueue method is not applicable for the argument and 2.)cannot cast from int to customers. Here is the code. The error is in the bolded lines towards the end
import java.util.Random;
class MyQueue<E> {
private int maxSize;
private int[] queArray;
private int front;
private int rear;
public MyQueue(int s) // constructor
{
maxSize = s+1; // array is 1 cell larger
queArray = new int[maxSize]; // than requested
front = 0;
rear = -1;
}
public void enqueue(int j) // put item at rear of queue
{
if(rear == maxSize-1)
rear = -1;
queArray[++rear] = j;
}
public int dequeue() // take item from front of queue
{
int temp = queArray[front++];
if(front == maxSize)
front = 0;
return temp;
}
public int peek() // peek at front of queue
{
return queArray[front];
}
public boolean isEmpty() // true if queue is empty
{
return ( rear+1==front || (front+maxSize-1==rear) );
}
public boolean isFull() // true if queue is full
{
return ( rear+2==front || (front+maxSize-2==rear) );
}
public int size() // (assumes queue not empty)
{
if(rear >= front) // contiguous sequence
return rear-front+1;
else // broken sequence
return (maxSize-front) + (rear+1);
}
}
class Customer { int arrive; // Time point that the customer arrived. int processTime; // Time duration that the customer will need to be served.
/**
* Default constructor
*/
public Customer() {
arrive = 0;
processTime = 0;
}
/**
* Set the arrival time point of the customer.
*
* #param Time
* point
*/
public Customer(int arrivalTime) {
arrive = arrivalTime;
// We set the processing time as a random integer between 1 and 3.
processTime = (int) (Math.random() * 3 + 1);
}
/**
* #return the arrival time point of the customer.
*/
public int getArrivalTime() {
return arrive;
}
/**
* #return the processing time of the customer.
*/
public int getProcTime() {
return processTime;
}
}
public class Simulator { /** * The main method of the class. * * #param args * Command line arguments. */ public static void main(String[] args) {
if (args.length != 3) {
System.out.println("usage: " + Simulator.class.getSimpleName()
+ " qCapacity simHours customPerHour");
System.out.println("Example: " + Simulator.class.getSimpleName()
+ " 10 1 30");
System.exit(-1);
}
// maximum size of queue
int qCapacity = Integer.parseInt(args[0]);
// number of simulation hours
int simHours = Integer.parseInt(args[1]);
// average number of customers per hour
int custPerHour = Integer.parseInt(args[2]);
// Run simulation
simulation(qCapacity, simHours, custPerHour);
}
private static void simulation(int qCapacity, int simHours, int custPerHour) {
// Constant
final int MIN_PER_HR = 60;
// A queue that will hold and manage objects of type Customer.
MyQueue<Customer> line = new MyQueue<Customer>(qCapacity);
// For how many cycles should the simulation run. We assume that each
// cycle takes one minute.
int cycleLimit = MIN_PER_HR * simHours;
// The average number of customers can arrive per minute
float custPerMin = ((float) custPerHour) / MIN_PER_HR;
// The number of customers that were turned away because the line
// (queue)
// was full at the time they arrived.
int turnAways = 0;
// Number of customers that arrived.
int customers = 0;
// Number of customers that were served.
int served = 0;
// Total number of customers that entered the line (queue).
int sumLine = 0;
// Waiting time until the next customer is served.
int waitTime = 0;
// Total time that all the customers waited in the line.
int lineWait = 0;
// Simulation
for (int cycle = 0; cycle < cycleLimit; cycle++) {
float j = custPerMin;
while (j > 0) {
if (newCustomer(j)) {
if (line.isFull()) {
turnAways++;
} else {
customers++;
Customer customer = new Customer(cycle);
**line.enqueue(customer);**
}
}
j = j - 1;
}
if (waitTime <= 0 && !line.isEmpty())
{
**Customer customer = (Customer) line.dequeue();**
waitTime = customer.getProcTime();
lineWait += cycle - customer.getArrivalTime();
served++;
}
if (waitTime > 0) {
waitTime--;
}
sumLine += line.size();
}
// Print the simulation results.
if (customers > 0) {
System.out.println("\nCustomers accepted: " + customers);
System.out.println(" Customers served: " + served);
System.out.println(" Customers waiting: " + line.size());
System.out.println(" Turnaways: " + turnAways);
System.out.println("Average queue size: " + (float) sumLine
/ cycleLimit);
System.out.println(" Average wait time: " + (float) lineWait
/ served + " minutes");
} else {
System.out.println("No customers!");
}
}
private static boolean newCustomer(float j) {
if(j > 1)
return true;
else
return (j > Math.random() );
}
It looks like your problem is with these two methods:
public void enqueue(int j) // put item at rear of queue
{
if(rear == maxSize-1)
rear = -1;
queArray[++rear] = j;
}
public int dequeue() // take item from front of queue
{
int temp = queArray[front++];
if(front == maxSize)
front = 0;
return temp;
}
If you had intended on the Queue to hold anything but integers, then you'll need to change the argument type / return type to reflect that.
**line.enqueue(customer);**
// 1.) my enqueue method is not applicable for the argument
Your enqueue method takes an int argmuent, yet you're trying to pass a Customer type to it. Maybe you want something like this: line.enqueue(customer.getSomething());. I can't really tell from your code.
**Customer customer = (Customer) line.dequeue();**
// 2.)cannot cast from int to customers
(Customer) line.dequeue();. Here you're casting Customer to int-line.dequeue()
Your dequque method return am int so basically you're saying that a Customer equals and int, which is impossible unless Customer isint, which it isn't
You want this:
Customer customer = new Customer(line.dequeue)
// Customer constructor takes an int value

Categories