Java - accumulator variable not incrementing after each loop iteration - java

When a car departs, the number of times a car was moved inside the garage should be shown along with the car plate. The output I am currently getting shows everything just fine, but the number of moves remains at 0 for all cars. I am having trouble figuring how to increment the variable and show the accumulated value in the output. How can I fix it?
Car class
package garagetester;
public class Car
{
private String licensePlate;//stores the license plate of the car as a String
private int movesCount = 0;//stores the number of times the car has been
//moved
public Car(String licensePlate)//builds a Car object with
{
this.licensePlate = licensePlate;
}
public String getLicensePlate() {
return licensePlate;
}
public int getMovesCount() {
return movesCount;
}
public void incrementMovesCount(int movesCount) {
movesCount++;
}
}//end of Car class
Garage Class
package garagetester;
public class Garage {
private Car[] garage; //array, stores Car objects
private final int LIMIT = 10; //determines length of the garage array
private int count;//number of cars in garage
public Garage() {
garage = new Car[LIMIT];
//creates an array of 10 elements
//first index = 0, last index = 9
public String arrive(Car newCar) {
String str = ""; //stores the result of the ARRIVE operation
/* If the garage is empty, the first car to arrive is parked in
the first empty spot closest to the exit*/
if (count != LIMIT) {
garage[count] = newCar;
count++;
str = newCar.getLicensePlate() + " has been parked";
} else {
str = "Sorry, " + newCar.getLicensePlate() + " the garage is full.";
}
return str;
}//end of arrive()
public String depart(String plate) {
String str = ""; //stores the result of executing the operation
int moves =0; //stores the number of times a car has been moved
boolean found = false; //flag
for (int i = 0; i < count - 1; i++) //for all elements in the array
{
//check if car with that plate number is in the garage
if (plate.equals(garage[i].getLicensePlate()))
{
found = true; //car has been found
if (found)//if found=true
{
//for all cars ahead of it
for (int j = i + 1; j < count; j++)//check if count or count-1
{
moves += garage[j].getMovesCount();
garage[j].incrementMovesCount(moves);
}
//for all cars behind it
for (int k = i; k > 0; k--) //or k=i-1, check when debugging
{
//move all cars behind it one position up
garage[k] = garage[k - 1];
}
str = plate + " has departed." + "it has been moved " + moves
+ " times. ";
count--; //decrease the number of cars in the garage by 1
}
else
{
str = "Sorry " + plate + " is not in the garage.";
}
}
}//end of for loop
return str;//prints the value stored in str
} //end of depart()
} //end of Garage class
Garage Tester Class
package garagetester;
import java.io.*;
import java.util.Scanner;
public class GarageTester
{
public static void main(String[] args) throws FileNotFoundException, IOException
{
//Initializes an array of 10 Car objects
Garage newGarage = new Garage();
//initializes a Scanner object to read data from file
Scanner scan = new Scanner(new File("garage.txt"));
//while there is tokens in the file
while (scan.hasNext())
{
String plate = scan.next();//stores the plate number read from file
String action = scan.next();//stores the action read from file
//evaluate action
switch (action) {
//if action has the value "ARRIVE"
case "ARRIVE":
Car aCar = new Car(plate);//create a Car object
System.out.println(newGarage.arrive(aCar));//call arrive method
break;
//if action has the value "DEPART"
case "DEPART":
System.out.println(newGarage.depart(plate));//call the depart method
break;
} //end of switch case
}//end of while
}//end of main()
} //end of GarageTester class

In your increment method should be like this in Car.java;
public void incrementMovesCount() {
this.movesCount++;
}
Also fix the other usage of this method. There is no need to send any data to new value. Car object has a movesCount field. That means , it can increment the movesCount itself.
If you dont want to change method signature , use this;
public void incrementMovesCount(int newMovesCount) {
this.movesCount = newMovesCount; //--newMovesCount refers to your calculation
}
but be carefull when using the last solution, because you are sending param as ;
moves += garage[j].getMovesCount(); //this moves never set to 0. Just equal to zero in the first iteration.
garage[j].incrementMovesCount(moves);
This is wrong i think. Because i suppose you wants to increment all of car's position. If you wants to apply first solution of my post, just fix compile error. But if you wants to apply second solution, just change this part like ;
garage[j].incrementMovesCount(garage[j].getMovesCount()+1);

Your parameter movesCount is shadowing the class member movesCount. In the following mutator:
public void incrementMovesCount(int movesCount) {
// movesCount++; --> this is incrementing the parameter
// either remove the parameter `movesCount` from this mutator
// since it's not being used, or do the following
this.movesCount++; // --> this refers to the class member movesCount
}

Related

How to get the data from a file into an array?

Over the passed couple of hours I have been working on an assigment with no luck in figuring it out. For reference I am going to post the instructions below and then explain what I have done.
Write a Java class that implements the StringSet interface (see
attached text document). One of your instance variables must be an
array of Strings that holds the data; you may determine what, if any
other instance variables you need. You will also need to implement the
required methods, one or more constructors, and any other methods you
deem necessary. I have also provided a tester class that you should be
able to run your code with.
So far I have created an implementation of the interface named MyStringSet. I have put all of the methods from the interface into my implementation and have written the code to what I think will work. My main problem is that I don't know how to put the data from the main method that is called into an array. The user types in a file and and then it is supposed to return word count and other methods. Since the file is being called from the tester class, I need to store that data into an array or an array list which I have already created. Below I have listed my current implementation and the tester class that I use. Any help is greatly appreciated!
My Implementation:
public class MyStringSet implements StringSet {
String[] myArray = new String [] {};
List<String> myList = Arrays.asList(myArray);
//default constructor
public MyStringSet(){
resize(5);
}
// precondition: larger is larger than current Set size
// postcondition: enlarges Set
public void resize(int larger) {
myArray = Arrays.copyOf(myArray, myArray.length + larger);
}
// postcondition: entry is inserted in Set if identical String
// not already present; if identical entry exists, takes no
// action. Calls resize if necessary
public void insert(String entry) {
Set<String> myArray = new HashSet<String>();
Collections.addAll(myArray, entry);
}
// postcondition: removes target value from Set if target is
// present; takes no action otherwise
public void remove(String target) {
if(target != null){
int n = 0;
int index = n;
for(int i = index; i < myArray.length - 1; i++) {
myArray[i] = myArray[i+1];
}
}
}
// precondition: Set is not empty
// postcondition: A random String is retrieved and removed from
// the Set
public String getRandomItem () {
String s = "String is Empty";
if (myArray != null) {
int rnd = new Random().nextInt(myArray.length);
return myArray[rnd];
}
else {
return s ;
}
}
// precondition: Set is not empty
// postcondition: the first item in the Set is retrieved and
// removed from the Set
public String getFirstItem () {
String firstItem = myList.get(0);
return firstItem;
}
// postcondition: returns true if target is present, false
// if not
public boolean contains(String target) {
if (target == null) {
return false;
}
else {
return true;
}
}
// postcondition: returns true if Set is empty, false if not
public boolean is_empty( ) {
if(myArray == null){
return true;
}
else {
return false;
}
}
// postcondition: returns total number of Strings currently in set
public int inventory() {
int total = myList.size();
return total;
}
// postcondition: returns total size of Set (used & unused portions)
public int getCapacity( ) {
int capacity = myArray.length;
return capacity;
}
}
Tester class:
public class SetTester
{
public static void main(String [] args) {
StringSet words = new MyStringSet();
Scanner file = null;
FileInputStream fs = null;
String input;
Scanner kb = new Scanner(System.in);
int wordCt = 0;
boolean ok = false;
while (!ok)
{
System.out.print("Enter name of input file: ");
input = kb.nextLine();
try
{
fs = new FileInputStream(input);
ok = true;
}
catch (FileNotFoundException e)
{
System.out.println(input + " is not a valid file. Try again.");
}
}
file = new Scanner(fs);
while (file.hasNext())
{
input = file.next();
words.insert(input);
System.out.println("Current capacity: " + words.getCapacity());
wordCt++;
}
System.out.println("There were " + wordCt + " words in the file");
System.out.println("There are " + words.inventory() + " elements in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
while (!words.contains(input))
{
System.out.println(input + " is not in the set");
System.out.println("Enter a value to remove from the set: ");
input = kb.nextLine();
}
words.remove(input);
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("The first 10 words in the set are: ");
for (int x=0; x<10; x++)
System.out.println(words.getFirstItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
System.out.println("5 random words from the set are: ");
for (int x=0; x<5; x++)
System.out.println(words.getRandomItem());
System.out.println("There are now " + words.inventory() + " elements in the set");
}
}
main problem is that I don't know how to put the data from the main method that is called into an array
You're doing that correctly already, following this simple example
StringSet words = new MyStringSet();
words.insert("something");
However, the contents of the insert method seem incorrect 1) you never check for identical values 2) never resizing 3) Collections.addAll doesn't do what you want, most likely
So, with those in mind, and keeping an array, you should loop over it, and check where the next non-null, non-identical value would be placed
// postcondition: entry is inserted in Set if identical String
// not already present; if identical entry exists, takes no
// action. Calls resize if necessary
public void insert(String entry) {
int i = 0;
while (i < myArray.length && myArray[i] != null) {
if (myArray[i].equals(entry)) return; // end function because found matching entry
i++;
}
if (i >= myArray.length) {
// TODO: resize()
insert(entry); // retry inserting same entry into larger array
}
// updates the next non-null array position
myArray[i] = entry;
}
As far as displaying the MyStringSet class goes, to see the contents of the array, you'll want to add a toString method

Cannot find ArrayList object

The NumberTile class models a number tile which is an arrayList of 4 integers, the TileGame class inserts a tile into the board, and a test class to start the game. A hand is an arraylist of 5 NumberTiles, but when I compile this, every time I reference to an ArrayList of NumberTile in TileGame, it cannot find the symbol NumberTile.
Do I need to create a package so it would recognize it? My instructor provided most of those statements and I cannot change them. I did not type the other methods because I do not think they are necessary.
Also, the line TileGame game = new TileGame(); says cannot find symbol. What would be the right way to initialize it?
I need any help I can get. Thank you.
Class TileGame:
public class TileGame
{
//provided by instructor
private ArrayList<NumberTile> board ;
// Creates an empty board
public TileGame()
{
//do not modify this method
board = new ArrayList<NumberTile>();
}
// Accessor for the board
public ArrayList<NumberTile> getBoard()
{
// Do not modify this method
return board ;
}
// Creates and returns a hand of 5 random number tiles
public ArrayList<NumberTile> getHand()
{
ArrayList<NumberTile> hand = new ArrayList<NumberTile>() ;
for (int a = 0; a < 5; a++)
{
hand.add(a, new NumberTile());
}
return hand;
}
// If the current tile fits in the board (without rotating) then
// return the index i of a tile in the board so that the current tile
// fits before ti for i = 0..k-1, or return k if the current tile fits
// after the last tile. If the tile does not fit, return -1
public int getIndexForFit(NumberTile currentTile)
{
NumberTile firstTile = board.get(0);
NumberTile lastTile = board.get(board.size() - 1);
if(firstTile.getLeft() == currentTile.getRight())
{
return 0;
}
else if (lastTile.getRight() == currentTile.getLeft())
{
return board.size() - 1;
}
else
{
return -1 ;
}
}
// Call the method getIndexForFit to see whether a tile can be inserted
// into the board. In this method the tile can be rotated. If the tile
// can be inserted, return true. If the tile does not fit after
// rotating (at most 3 times), return false.
public boolean canInsertTile(NumberTile currentTile)
{
//call get index for fit
int canInsert = getIndexForFit(currentTile);
boolean canInsertOrNot = false;;
//if true, modify index
if(canInsert == -1)
{
//rotate
for (int rotations = 0; rotations < 3; rotations++)
{
currentTile.rotate();
int didRotationWork = getIndexForFit(currentTile);
if (didRotationWork == -1)
{
continue;
}
else if (didRotationWork != -1)
{
canInsertOrNot = true;
}
}
return false;
}
else if(canInsert != -1)
{
return true;
}
return canInsertOrNot;
}
// Make a move. I.e. if a tile in the hand fits on the board
// then remove it from the hand and place it in the board. If no tile
// from the hand fits, then add another tile to the hand
public void makeMove(ArrayList<NumberTile> hand)
{
boolean fits;
for (int x = 0; x < hand.size(); x++)
{
//call caninterserttile
fits = canInsertTile(hand.get(x));
if(fits)
{
int index = getIndexForFit(hand.get(x));
board.add(index, hand.get(x));
hand.remove(x);
break;
}
else
{
hand.add(hand.size() -1, new NumberTile());
}
}
}
public String toString()
{
// Do not modify this method
return board.toString() ; // ArrayList as a String
}
} // end of TileGame class
Class NumberTile:
public class NumberTile
{
public ArrayList<Integer> tile = new ArrayList<>();
// Constructs a NumberTile object using 4 random integers in the
// range 1 to 9
public NumberTile()
{
Random generator = new Random() ;
for (int a = 0; a < 4; a++)
{
int random = generator.nextInt(9);
tile.add(a, random);
}
}
// Rotate the tile 90 degrees
public void rotate()
{
int temp = tile.get(0);
tile.set(0, tile.get(1));
tile.set(1, tile.get(3));
tile.set(3, tile.get(2));
tile.set(2, temp);
}
public int getLeft()
{
// Do not modify this method
return tile.get(0) ;
}
public int getRight()
{
// Do not modify this method
return tile.get(2) ;
}
public String toString()
{
String out = "";
out += " "+tile.get(0)+" ";
out += tile.get(1) + " " + tile.get(2);
out += " "+tile.get(3)+" ";
return out;
}
} // end of NumberTile class
Class TileGameTester:
public class TileGameTester {
public static void main(String[] args){
TileGame game = new TileGame();
boolean winner = false;
//get two hands
ArrayList<NumberTile> hand1 = game.getHand();
ArrayList<NumberTile> hand2 = game.getHand();
//create an empty board
System.out.println(game.getBoard());
do{
//make moves
game.makeMove(hand1);
game.makeMove(hand2);
//check if they won
if (hand1.isEmpty() || hand2.isEmpty())
{
winner = true;
}
}while(!winner);
hand1.toString();
hand2.toString();
if (hand1.isEmpty() && hand2.isEmpty())
{
System.out.println("It is a tie!");
}
else if (hand1.isEmpty())
{
System.out.println("Player 1 won!");
}
else if (hand2.isEmpty())
System.out.println("Player 2 won!");
}
}
Though it is incomplete so i am not sure if you are adding data to the arraylist or not but if you are getting Symbol not found .
I am also not able to see any import statements . Did you import the objects
eg TileGameTester should have import -> import com.something.TileGame and import com.something.NumberTile
also check if you have import statement in TileGame and common imports like arraylist
I think you may need to insert "import java.util.Random;" and "import java.util.ArrayList;" between your package declaration (if you have one) and the class declaration in the files where these are used.
You can import TileGame class to TileGameTester class that might solve your issue.

Removing item from ArrayList using remove(<index>) or remove(<objectRef>)

I want to create a program which displays current staff in the ArrayList before asking the user for input of a payroll number they'd like to remove. User then should input the payroll number of one of the three staff members and press enter. Upon pressing enter, the program should remove that particular staff member from the array list and display the entire list again (missing out the staff member they've deleted obviously). If the user no longer wishes to remove any payroll numbers, the payroll number entry should be 0 and should then display the contents of the list again.
The problem I'm having is with the remove part.
I've been recommended of two ways of achieving this:
This 'search' method should return either the position within the ArrayList (so that remove(<index>) may be used) or a reference to the object (so that remove(<objectRef>) may be used). If the staff member is not found, then the search method should return -1 (if remove(<index>) is being used) or null (if remove(<objectRef>) is being used).
However I am not sure how to implement this in Java.
Here is my file structure:
ArrayListTest.java
import java.util.*;
import personnelPackage.Personnel;
public class ArrayListTest
{
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args)
{
long searchQuery;
ArrayList<Personnel> staffList = new ArrayList<Personnel>();
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
for (Personnel person:staff)
staffList.add(person);
do
{
showDisplay(staffList);
System.out.print("\nPlease enter a payroll number to search: ");
searchQuery = keyboard.nextLong();
searchForPayrollNumber(staffList, searchQuery);
}while(!(searchQuery == 0));
}
private static void showDisplay(ArrayList<Personnel> staffList)
{
System.out.print("\n------------- CURRENT STAFF LIST -------------\n");
for (Personnel person : staffList)
{
System.out.println("Payroll number: " + person.getPayNum());
System.out.println("Surname: " + person.getSurname());
System.out.println("First name(s): " + person.getFirstNames() + "\n");
}
}
public static void searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
long index = staffList.indexOf(searchQuery);;
for (Personnel person: staffList)
{
if (person.getPayNum() == searchQuery)
{
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + person.getFirstNames());
System.out.println("\nSurname: " + person.getSurname());
System.out.print("\n-----------------------------------------------");
staffList.remove(index);
return;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return;
}
}
Personnel.java (in its own package named personnelPackage)
package personnelPackage;
public class Personnel
{
private long payrollNum;
private String surname;
private String firstNames;
public Personnel(long payrollNum, String surname, String firstNames)
{
this.payrollNum = payrollNum;
this.surname = surname;
this.firstNames = firstNames;
}
public long getPayNum()
{
return payrollNum;
}
public String getSurname()
{
return surname;
}
public String getFirstNames()
{
return firstNames;
}
public void setSurname(String newName)
{
surname = newName;
}
}
Consider using Iterator for search and removal:
Iterator<Personnel> i = staffList.iterator();
while (i.hasNext()) {
Personnel p = i.next();
if (p.getPayNum() == searchQuery) {
// print message
i.remove();
return p;
}
}
return null;
If using List#remove() is strictly required, return found personnel p and call if (p != null) staffList.remove(p):
public static Personnel searchByPayNum(List<Personnel> ps, long num) {
for (Personnel p : ps) {
if (p.getPayNum() == num)
return p;
}
return null;
}
And in caller code:
Personnel p = searchByPayNum(staffList, query);
if (p != null) {
// log
staffList.remove(p);
}
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery) {
//long index = staffList.indexOf(searchQuery);
for(int i = 0; i < staffList.size(); i++) {
if (staffList.get(i).getPayNum() == searchQuery) {
System.out.print("\n------------- Staff member found and removed! -------------");
System.out.println("\n\nFirst Name(s): " + staffList.get(i).getFirstNames());
System.out.println("\nSurname: " + staffList.get(i).getSurname());
System.out.print("\n-----------------------------------------------");
//staffList.remove(i);
return i;
}
}
System.out.print("\n------------- No staff members found. Program terminated -------------");
return -1;
}
Your search method shouldn't return void. It should return int or long instead,
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
int index = -1;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
index = i;
System.out.print("\n------------- Found Staff member at position " + index + " in the list");
break;
}
}
if (index != -1){
staffList.remove(index);
System.out.print("\n------------- Removed the staff member");
}
return index;
}
Last approach returned the index. Now when you want to return the object:
public static long searchForPayrollNumber(ArrayList<Personnel> staffList, long searchQuery)
{
Personnel p = null;
for (int i = 0; i < staffList.size(); i++){
if(staffList.get(i).getPayNum() == searchQuery){
p = staffList.get(i);
break;
}
}
staffList.remove(p);
return p;
}
You must know that after removing it from the list, It will shift any subsequent elements to the left (subtracts one from their indices).
Also, just a suggestion:
Instead of
Personnel[] staff =
{new Personnel(123456,"Smith","John"),
new Personnel(234567,"Jones","Sally Ann"),
new Personnel(999999,"Black","James Paul")};
Why not
staffList.add(new Personnel(123456,"Smith","John"));
staffList.add(new Personnel(234567,"Jones","Sally Ann"));
staffList.add(new Personnel(999999,"Black","James Paul"));
This is just an advice. Since searching and removing are your primary goals, ArrayList is not the right collection to use.
Create a Hashmap with ID as key and Personnel object as value. This will help in identifying the Personnel in O(1) time and removal as well.
ArrayList should be used only when you know the index to read value. It then does that in O(1). If not, it is O(n) and not as efficient as HashMap.

CompareTo bubble sort

I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}

Handling a Circular Queue that is Made Up of Objects

I am trying to create a circular queue that will hold objects. The idea is the user will either buy or sell stock, and each time a stock is purchased, that object will hold the amount of stock purchased and the price is was purchased for in the queue. This queue is an array based queue with a size of 32 and every time the user selects to buy, it will fill another slot.
If the user elects to sell stock, the number of stocks sold will be subtracted from the first object unless the user sells more stock than the first slot contains, in that case it will subtract from the subsequent slot. Once the slot has had all of it's stock sold...aka it has no more shares, that object can be dequeued and it will free up a slot to buy stock once the queue comes around to that position
I am struggling on handling the object types. Especially when I try to dequeue just for testing to see if I can dequeue properly.... I will get the last slot when I dequeue even though I am pretty sure the method is right, I am just having difficulty handling the classes/objects.
NOTE: I must manually create the array/queue, so I can't use the Java built in array
StockTran class.......Has Stock as a nested class
import java.util.Scanner;
//Once you reach the end of the array, you are going to get an out of bounds exception if you try to enqueue again
//So if there are any open boxes on the very front of the array, say a[0] is empty, you can place the extra array spot at a[0]
//Then keep going
//You can handle the overflow and make the array circular or at least get the size by using (get + put)%size...So if (4+5)%8
//the answer is 1... meaning the size is 1.
//Create a total variable thats adds up the total of shares each spot in the array has...This way you can say you don't have
//that many shares if they try to sell more than what you actually have....Also look at the amount of shares each spot has
//and only dequeue when the total of shares for that spot is used up..."Only dequeue a truck when it's empty"
//User is prompted to enter in either b, s, c, or q.....
//b = buy shares, s = sell shares, c = capital gain from buying and selling q = quit the program
//Must be formatted by letter (space) number (space) number........ EX: b 10 10 .... this will buy 10 shares at $10 each
//This is the class I am storing in the queue.....Can call methods on it to get out crucial data
class Stock {
public int getShares() {
return shares;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
private int shares;
private int price;
// Get price Get Shares set price get set price
public void stockTran() {
// total gain,
}
}
//Class that handles the user's input, should handle the math for profit, subtracting, etc....Basically the class that
//links all the other classes/methods together
public class StockTran {
// Declaring variables
private MyQueue<Stock> queueArray; // Size of Array/Queue is 32
static String firstCommand; // The first token of the scanner...Looks
// whether b,s, or c
static int shares; // How many shares that are bought/sold
static int price; // The price those shares are bought/sold at
static int netProfit = 0; // Initializing the profit so it can be
// added/subtracted later
static int put, get = 0; // Declaring the front and rear portions of the queue
static int total = 0; // Initial number of elements in the array, this will
// increase/decr
public static void main(String[] args) {
StockTran eg = new StockTran();
eg.queueArray = new MyQueue<Stock>(32);
Stock test = new Stock();
// Prompts the user to enter an input
// The if/else if ladder is used to call the correct methods based on
// the user input..Reads by looking
// at the tokens
while (true) {
Scanner reader = new Scanner(System.in);
System.out.println("Enter the proper formatted commands ");
firstCommand = reader.next();
if (firstCommand.equalsIgnoreCase("b")) {
shares = reader.nextInt();
price = reader.nextInt();
test.setPrice(price);
test.setShares(shares);
eg.queueArray.enqueue(test);
System.out.println("Price: " + test.getPrice());
System.out.println("Shares: " + test.getShares());
System.out.println("Size: " + eg.queueArray.size());
// System.out.println("Buying " + shares + " shares" + ", " +
// "$" + price + " each");
} else if (firstCommand.equalsIgnoreCase("s")) {
System.out.println("dequeued price: " + ((Stock) eg.queueArray.dequeue()).getPrice());
System.out.println("dequeued shares: " + ((Stock) eg.queueArray.dequeue()).getShares());
System.out.println("Size: " + eg.queueArray.size());
}
else if (firstCommand.equalsIgnoreCase("c")) {
System.out.println("Capital gain");
} else if (firstCommand.equalsIgnoreCase("q")) {
System.out.println("Quitting");
break;
} else {
System.out.println("Command Not Recognized!");
}
}
}
// This method will either add or subtract from the total profit depending
// upon the buying and selling....Not finished yet
public int calculate(int netProfit) {
int i = 0;
while (i < shares) {
i++;
}
return netProfit;
}
}
Queue Interface
public interface Queue <E> {
//Gets the size of array queue
public int size();
//Checks if the queue is empty
public boolean isEmpty();
//Looks at the first item
public Object front() throws EmptyQueueException;
//Puts an element at the end of the array
// public void enqueue (Node element);
public void enqueue (E element);
//Removes an element from the front of the array
public Object dequeue() throws EmptyQueueException;
}
MyQueue class
// Creates the node and allows methods to assign, get the next element, and set elements
// for the node
//So you create a node class with quanitity and price.... Has to be an object
public class MyQueue <E> implements Queue <E>
{
//Instance variables
private Object [] queue;
private int front, rear = 0; //Pointers for the queue....Locates where the next enqueue/dequeue spot should be
private int max = 32; //Size of my queue
private int size;
public MyQueue(int max)
{
this.queue = new Object[max];
}
#Override
public int size() {
// TODO Auto-generated method stub
size = (rear - front)%32;
return (rear - front)%32;
}
#Override
public boolean isEmpty() {
// TODO Auto-generated method stub
if (front == rear)
return true;
else
return false;
}
//Gets the front object of the queue
#Override
public Object front() throws EmptyQueueException {
// TODO Auto-generated method stub
return queue[front];
}
//Adds an element to the end of the queue
#Override
public void enqueue(E element) {
// TODO Auto-generated method stub
this.queue[this.rear%this.max] = element;
if (rear < 32)
rear++;
else
rear = 0;
System.out.println("Font is: " + front);
System.out.println("Rear is: " + rear);
}
//Removes an element from the front of the queue
#Override
public Object dequeue() throws EmptyQueueException {
Object temp = null;
if (isEmpty() == true){
throw new EmptyQueueException("Empty Queue!");
}
if(size() > 0 && front != size){
temp = queue[front];
System.out.println(": " + temp);
front = front + 1;
}
else if(front == size())
front = 0;
System.out.println("Font is: " + front);
System.out.println("Rear is: " + rear);
return temp;
}
}
Thank you!

Categories

Resources