java program is printing objects in the wrong order - java

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);

Related

Efficiently Looping through Object array with Multiple Variable types in Java

I'm writing a simple script in Java that is calling another class that holds all my information.
I am holding my information in the called class in Object[] Arrays and I am planning on calling the script to fetch that array.
Right now the function looks like this.
public void tradeShop() {
/*
*Variables must be initialized in order to call shopTrader
*The values are just non-null placeholders and they are
*replaced with the same values in the tradeValues Object array.
*/
String targetName = "NPC Name";
String itemName = "Item Name";
int itemQuantity = 1;
int minCoins = 1;
int minBuy = 1;
boolean stackable = false;
Object[] tradeValues = shop.defaultValues;
for (int i = 0; i < tradeValues.length; i++) {
if(String.class.isInstance(tradeValues[i])) {//String check
if(i==0) { //0 is NPC Name
targetName = (String) tradeValues[i];
} else if (i==1) { //1 is Item Name
itemName = (String) tradeValues[i];
}
} else if (Integer.class.isInstance(tradeValues[i])) { //Int check
if(i==2) { //2 is Item Quantity
itemQuantity = (Integer) tradeValues[i];
} else if (i==3) { //3 is Minimum coins
minCoins = (Integer) tradeValues[i];
} else if (i==4) { //4 is the Minimum Buy limit
minBuy = (Integer) tradeValues[i];
}
} else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check
stackable = (Boolean) tradeValues[i]; //5 is the item Stackable
} else {
//TODO: Implement exception
}
}
//Calls ShopTrader() method shopTrader
ShopTrader trade = new ShopTrader();
trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);
}
I feel like using a for loop like this is not the correct way for me to be looping through these Objects, I shouldn't have to check i== for each variable.
Also it hinders me from adding overloads to the shopTrader method as I would have to write an entirely new for loop for each overload.
Does anyone have a more elegant solution for getting the variables from this array?
I think that instead of storing all of your information in Object[], you may want to create a new class to act as a data structure i.e.
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
You can then just access the information directly
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...

Get upperbound and lower bound using a mid range

I am trying to find he upper and lower bound of the data below
0,0
4,0
12,1
16,1
16,2
18,4
24,5
26,8
28,9
If my mid-range is 5 . I need to group my data as
1 st column = [0,4,12,16,16],[18,24,26,28] (rest of the values can be just added to list even if it is not of size 5)
But instead of storing every elements into an array. I would like to store only [0,16],[18,28].
Like wise for 2 nd column [0,2],[4,9].
But using my current code I am only getting [0,16].
Below is my code
import java.util.ArrayList;
public class Trail {
public static void main(String[] args) {
ArrayList<String> inputvalues = new ArrayList<String>();
inputvalues.add("0:0.0");
inputvalues.add("0:4.0");
inputvalues.add("0:12.0");
inputvalues.add("0:16.0");
inputvalues.add("0:16.0");
inputvalues.add("0:18.0");
inputvalues.add("0:24.0");
inputvalues.add("0:26.0");
inputvalues.add("0:28.0");
inputvalues.add("1:0.0");
inputvalues.add("1:0.0");
inputvalues.add("1:1.0");
inputvalues.add("1:1.0");
inputvalues.add("1:2.0");
inputvalues.add("1:4.0");
inputvalues.add("1:5.0");
inputvalues.add("1:8.0");
inputvalues.add("1:9.0");
/*
* Iterate through data
*/
int counter = 0 ;
double prevV = 0;
String currKey = "";
String prevKey = "";
ArrayList<Double> arr = new ArrayList<>();//REsult with upperbound and lower bount
int splitRange = 5;
for(String lst : inputvalues){
counter++;
System.out.println("\n*********lst********** "+lst);
String[] parts = lst.split(":");//key
currKey = parts[0];//value
double v = Double.parseDouble(parts[1]);
if(prevKey.equals ("")){
/*
* prev value empty.
* Initial value
*/
arr.add(v);
System.out.println("Initial range "+arr);
}
else if(prevKey.equals(currKey)){
/*
* Both incoming values are same
*/
System.out.println("----------same key-----------");
if(counter == splitRange){
arr.add(v);
System.out.println("RESULT-------->"+arr);
counter = 0;
}
else{
prevV = v;
// System.out.println("Previous v "+prevV);
}
/*
* initial counter
*/
if(counter == 1 ){
arr = new ArrayList<>();
arr.add(v);
// System.out.println("counter equals 1 "+arr);
}
}
else if (!prevKey.equals(currKey)){
if(counter != splitRange){
// System.out.println("In not equalls");
arr = new ArrayList<>();
arr.add(prevV);
// System.out.println("arrr "+arr);
}
counter = 0;
if(counter == 1 ){
arr = new ArrayList<>();
arr.add(prevV);
// System.out.println("counter equals 1 "+arr);
}
counter++;
/*
* previous value
*/
// System.out.println("Previous v "+prevV);
arr.add(prevV);
// System.out.println("prev not equal to current "+arr);
}
prevKey = currKey;
}
}
}
Please help me to figure out the same.

How to sort a linked list with objects and private variables

I am going to be honest and up front here. This is homework, but I have become desperate and am looking for anyone to assist me. I have been working on this off and on for over a month and have gone to my instructor multiple times. Basically this program needs to create and sort a linked list that has an int, string and double in each node. It needs to be able to sort by each data type as well as print in input order but once I figure one out I can transfer it to the other data types. Please, everything needs to be "hand made", please do not use any built in commands as I need to create everything as per my instructor's demands.
I attempted to make the linked list and then sort it, but I ran into a problem so I decided to try and sort the list as I create it.
For example: Input the first node, then input the next node in front/behind the first, then put the next where it needs to go... and so forth.
Here is my code (I only focus on the strings):
String repeat = "y";
list1 fChr = null;
list1 p = fChr;
list1 copy = null;
//list1 dCopy = null;
//list1 iCopy = null;
list1 fd = fChr;//front of the double list
list1 fi = fChr;//front of the integer list
list1 fStr = fChr;//front of the string list~
list1 pStr = fStr;
boolean inserted = false;
int iii = 0;
String sss = "";
double ddd = 0.0;
while(repeat.equals("y"))//while the user agrees to adding a new node
{
if(fChr == null)// if the front is empty
{
fChr = new list1();//create a new node by calling object and sets it as the front
p = fChr;
copy = fChr;
sss = fChr.GetS();
iii = fChr.GetI();
ddd = fChr.GetD();
copy.SetS(sss);
copy.SetI(iii);
copy.SetD(ddd);
System.out.println("(1)");
}
else
{
System.out.println("(2)");
if(p!=null)
{
System.out.println("p = "+ p.GetS());
if(p.next != null)
{
System.out.println("p.next = "+ p.next.GetS());
System.out.println("p.next.next = "+ p.next.next.GetS());
}
}
p = fChr;
while(p.next != null)//finds the end of the Linked list
{
System.out.println("(3)");
p = p.next;//moves the pointer p down the list
}
list1 NextNode = new list1();//
p.next = NextNode;
sss = NextNode.GetS();
iii = NextNode.GetI();
ddd = NextNode.GetD();
copy = NextNode;
String gg = "hi";//tests to see if the setter is actually changing the value inside copy(it is not, it prints b)
copy.SetS(gg);
copy.SetI(iii);
copy.SetD(ddd);
System.out.println(copy.GetS());
System.out.println("p = "+ p.GetS());
}
pStr = fStr;
//System.out.println(copy.GetS()+"*");
inserted = false;
if(fStr == null)
{
System.out.println("(4)");
fStr = copy;//fStr = fChr;
inserted = true;
//System.out.println("p.next.next = "+ p.next.next.GetS());
}
else if(copy.GetS().compareTo(fStr.GetS()) < 0)
{
System.out.println("(5)");
//System.out.println("1)p.next.next = "+ p.next.next.GetS());
copy.next = fStr;//ERROR ON THIS LINE
System.out.println("2)p.next.next = "+ p.next.next.GetS());
System.out.println("fChr.next: "+fChr.next.GetS());
fStr = copy;
System.out.println("3)p.next.next = "+ p.next.next.GetS());
inserted = true;
System.out.println("p = "+ p.GetS());
System.out.println("p.next = "+ p.next.GetS());
System.out.println("4)p.next.next = "+ p.next.next.GetS());
}
else if(fStr.next == null && fStr != null)
{
System.out.println("(6)");
fStr.next = copy;
inserted = true;
}
else
{
System.out.println("(7)");
pStr = fStr;
System.out.println("RIP (8)");
while(pStr.next != null && inserted == false)
{
System.out.println("(9)");
System.out.println("RIP");
if(copy.GetS().compareTo(pStr.next.GetS()) < 0)//if it goes between 2 nodes
{
System.out.println("(10)");
copy.next = pStr.next;
pStr.next = copy;
inserted = true;
}
else
{
System.out.println("(11)");
pStr = pStr.next;
}
if(pStr.next == null && inserted == false)// it goes at the end(not necessary bc of the (in order) part)
{
System.out.println("(12)");
pStr.next = copy;
}
}
}
repeat = JOptionPane.showInputDialog("Would you like to add a node [y/n]");
System.out.println("End of Loop");
}
System.out.println(fStr.GetS());
PrintMenu(fChr, fi, fd, fStr);// sends the user to the menu screen
}
From all of my print statements I have (what I think) found the problem. This code runs through twice and upon hitting "y" for the third time, prints "(3)" in an infinite loop. I have found that (say the input for the strings is "c" then "b") "p" is equal to "c", p.next is equal to "b" and p.next.next is equal to "c". So, p is in an infinite loop. I have no idea why it does this, I have a theory that it could be because the front(fChr) changes and then "p" points to it and is just kinda drug along. I also just realized that me trying to set "copy" equal to "NextNode" was unsuccessful and copy just holds the value inside p.next(which is NextNode). That seems correct, but when I try to put something else in, it doesn't work. I could be testing this incorrectly and in that case the setter is correct. Setting is one of the main problems that I seem to be having. I will try to answer as many questions as I can if anyone has any.
Also here is the object in case you would like to see it. Thank you for your time, any help will be appreciated. Please if possible try to keep it relatively simple this is a high school assignment and I am so close and am stumped on how to fix what is wrong. Also, you may have noticed, but I have to use private variables. I am not asking for someone to give me a program that works, I am just asking if you know why what is going wrong is happening and if you know how to fix it. Thank you from the bottom of my heart!
import javax.swing.JOptionPane;
public class list1
{
private int i;
private String s;
private double d;
private String ss = null;
private int ii = 0;
private double dd = 0.0;
list1 next = null;
public list1()
{
String str;
s=JOptionPane.showInputDialog("Enter a String");
String temp =JOptionPane.showInputDialog("Enter an Integer");
i = Integer.parseInt(temp);
String temp2 =JOptionPane.showInputDialog("Enter a Double");
d = Double.parseDouble(temp2);
}
public double GetD()
{
return d;
}
public String GetS()
{
return s;
}
public int GetI()
{
return i;
}
public void SetS(String x)
{
ss = x;
}
public void SetI(int y)
{
ii = y;
}
public void SetD(double z)
{
dd = z;
}
}

removeZero() method when creating linkedlist?

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.

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