java - Queue method help needed - java

I am doing a project in Java and I need to create a queue method.
Every time someone is added to a room, they need to be added to the queue.
I nee to create my own queue object in your program and write methods within the object to add to queue and take from queue.
Every time a customer is added to a room it should use the
queue object method to add the customer’s name to the queue.
When the user selects to display the names of the last 3 customers the code should remove them from the queue one by one (first in first out) and display them as they are removed.
The queue should be based on an array and hold 7 items.
When the queue items reach the end of the array they should be added to the start or the array.
If the queue becomes full then an error message should be displayed and the oldest queue item should be automatically removed and displayed.
This is the main body:
package hotelcoursework2;
import java.util.*;
public class HotelCourseWork2 {
public static void main(String[] args) {
Room[] myHotel = new Room[10];
Queue mq = new Queue();
int guests = 0;
String roomName = null;
int roomNum = 0;
String letter = "";
for (int i = 0; i < myHotel.length; i++) {
myHotel[i] = new Room();
}
do {
System.out.println("Press E to display empty rooms");
System.out.println("Press A to add customers to room");
System.out.println("Press V to view all rooms ");
System.out.println("Press D to delete customers from rooms");
System.out.println("Or enter 1 to add to queue, 2 to take from queue or 3 display queue");
System.out.println("Press S to save");
System.out.println("Press L to load");
System.out.println("Press X to exit");
System.out.println("Enter a Letter: ");
Scanner scan = new Scanner(System.in);
letter = scan.next();
if (letter.equals("A")) {
add(myHotel, roomNum, roomName, guests);
mq.addqueue();
}
if (letter.equals("V")) {
view(myHotel);
}
if (letter.equals("E")){
empty(myHotel);
}
if(letter.equals("D")){
delete(myHotel, roomNum);
mq.takequeue();
}
if (letter.equals("S")){
}
if(letter.equals("3")){
mq.displayqueue();
}
} while (letter.charAt(0) != 'X');
System.out.println("Exit successfull");
}
private static void add(Room myHotel[], int roomNum, String roomName, int guests) {
Scanner input = new Scanner(System.in);
System.out.println("Enter room number (0-9) or 10 to stop:");
roomNum = input.nextInt();
if (roomNum == 10) {
System.out.println("Exit successful");
System.exit(0);
}
System.out.println("Enter name for room " + roomNum + " :");
roomName = input.next();
myHotel[roomNum].setName(roomName);
System.out.println("Enter how many guests: ");
guests = input.nextInt();
myHotel[roomNum].setGuestsInRoom(guests);
System.out.println("Add customers to queue: ");
for (int i = 0; i < 10; i++) {
System.out.println("Customer " + myHotel[i].getName() + " has been allocated to room " + i
+ " with " + myHotel[i].getGuestsInRoom() + " guests. ");
}
}
private static void view(Room myHotel[]) {
for (int i = 0; i < 10; i++) {
System.out.println("room " + i + " occupied by " + myHotel[i].getName() );
}
}
private static void empty(Room myHotel[]) {
for (int i = 0; i < 10; i++) {
if (myHotel[i].getName().equals("no-one")) {
System.out.println("room " + i + " is empty");
}
}
}
private static void delete(Room myHotel[], int roomNum){
Scanner input = new Scanner(System.in);
System.out.println("Enter room number you want to delete a customer from: ");
roomNum = input.nextInt();
myHotel[roomNum].setName("no-one");
}
}
This is the class I have created for the queue but now I am stuck.The queue should be first in first out.
package hotelcoursework2;
import java.util.Scanner;
public class Queue {
// be careful - this queue can go over the end of the array
//the array should be used in a circular way
private static String qitems[] = new String[7];
private static int front = 0, end = 0;
static void addqueue() {
Scanner input = new Scanner(System.in);
System.out.print("Enter someone to the queue :");
qitems[end] = input.next();
end++;
}
static void takequeue() {
if (end > front) {
System.out.println("Person remove :" + qitems[front]);
front++;
} else {
System.out.println("Empty queue");
}
}
static void displayqueue() {
System.out.println("Queue display: ");
for (int look = front; look < end; look++) {
System.out.print(" " + qitems[look]);
}
System.out.println("");
}
}

So basically you want to know how to implement a simple queue.
Unless you have to, using an array is more complicated because you have to deal with resizing the array and moving its contents about.
The simplest queue structure is a linked list, like this:
public class Queue<T>
{
private Node head;
private Node tail;
public void add(T value)
{
if (head == null)
{
head = new Node(null, value);
tail = head;
}
else
{
tail = new Node(tail, value);
}
}
public T peek()
{
return head == null ? null : head.value;
}
public T take()
{
if (head == null)
{
return null;
}
else
{
T value = head.value;
head = head.next;
return value;
}
}
#Override
public String toString()
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("[");
Node current = head;
while (current != null)
{
stringBuilder.append(current.value).append(",");
current = current.next;
}
return stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), "]").toString();
}
private class Node
{
private Node next;
private T value;
public Node(Node previous, T value)
{
this.value = value;
if (previous != null)
{
previous.next = this;
}
}
}
}
This class keeps reference to the head and tail Nodes adjusting references in the Node chain when new values are added and modifying the head reference when values are taken.

Related

how to remove and search an object by name from linked list in java

I can write the function to delete at position I choose. But I have problems when I write the function to delete the employee by input of the employee's name. I still have the same problem with the search function. Use case 7, 8 in menu to perform delete and search function. Can anybody help me with my code?
Here's my source code:
import java.util.Scanner;
import java.io.Serializable;
/* Class Node */
class Employee implements Serializable{
int ID;
String name;
String address;
Employee(int emp_ID, String emp_name, String emp_address){
ID = emp_ID;
name = emp_name;
address = emp_address;
}
public void print(){
System.out.println(ID);
System.out.println(name);
System.out.println(address);
}
#Override
public String toString() {
return ID + "-" + name + "-" + address;
}
}
class Node
{
protected Employee emp;
protected Node link;
public Object name;
public Node in;
/* Constructor */
public Node()
{
link = null;
emp = null;
}
/* Constructor */
public Node(Employee e,Node n)
{
emp = e;
link = n;
}
/* Function to set link to next Node */
public void setLink(Node n)
{
link = n;
}
/* Function to set data to current Node */
public void setData(Employee e)
{
emp = e;
}
/* Function to get link to next node */
public Node getLink()
{
return link;
}
/* Function to get data from current Node */
public Employee getData()
{
emp.print();
return null;
}
}
/* Class linkedList */
class linkedList
{
protected Node start ;
protected Node end ;
public int size ;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of the list */
public int getSize()
{
return size;
}
/* Function to insert element at the begining */
public void insertAtStart(Employee e)
{
Node nptr = new Node(e,null);
nptr.setLink(start);
if(start == null)
{
start = nptr;
nptr.setLink(start);
end = start;
}
else
{
end.setLink(nptr);
start = nptr;
}
size++ ;
}
/* Function to insert element at end */
public void insertAtEnd(Employee e)
{
Node nptr = new Node(e,null);
nptr.setLink(start);
if(start == null)
{
start = nptr;
nptr.setLink(start);
end = start;
}
else
{
end.setLink(nptr);
end = nptr;
}
size++ ;
}
/* Function to insert element at position */
public void insertAtPos(Employee e , int pos)
{
Node nptr = new Node(e,null);
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink() ;
ptr.setLink( nptr );
nptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size++ ;
}
/* Function to delete element at position */
public void searchByName(){
}
public void deleteByName(){
}
public void deleteAtPos(int pos)
{
if (size == 1 && pos == 1)
{
start = null;
end = null;
size = 0;
return ;
}
if (pos == 1)
{
start = start.getLink();
end.setLink(start);
size--;
return ;
}
if (pos == size)
{
Node s = start;
Node t = start;
while (s != end)
{
t = s;
s = s.getLink();
}
end = t;
end.setLink(start);
size --;
return;
}
Node ptr = start;
pos = pos - 1 ;
for (int i = 1; i < size - 1; i++)
{
if (i == pos)
{
Node tmp = ptr.getLink();
tmp = tmp.getLink();
ptr.setLink(tmp);
break;
}
ptr = ptr.getLink();
}
size-- ;
}
/* Function to display contents */
public void display()
{
System.out.print("\nEmployee Management= ");
Node ptr = start;
if (size == 0)
{
System.out.print("empty\n");
return;
}
if (start.getLink() == start)
{
System.out.print(start.getData()+ "\n");
return;
}
System.out.print(start.getData()+ "" + "\n");
ptr = start.getLink();
while (ptr.getLink() != start)
{
System.out.print(ptr.getData()+ "" + "\n");
ptr = ptr.getLink();
}
System.out.print(ptr.getData()+ "\n");
}
}
/* Class CircularSinglyLinkedList */
public class CurrilarLinkedList
{
public static void main(String[] args)
{
int ID = 0;
String name = null;
String address = null;
Employee emp = null;
Scanner scan = new Scanner(System.in);
/* Creating object of linkedList */
linkedList list = new linkedList();
System.out.println("Circular Singly Linked List Test\n");
char ch;
/* Perform list operations */
do
{
System.out.println("\nCircular Singly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
System.out.println("7. delete by name");
System.out.println("8. search by name");
int choice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.print("Please input an Employee \n");
Scanner myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
list.insertAtStart(emp);
break;
case 2 :
System.out.print("Please input an Employee \n");
myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
list.insertAtEnd(emp);
break;
case 3 :
System.out.println("Enter position");
int pos = scan.nextInt() ;
System.out.print("Please input an Employee \n");
myScanner = new Scanner(System.in);
System.out.println("Please input an Employee ID");
ID = myScanner.nextInt();
myScanner.nextLine();
System.out.println("Please input an Employee Name");
name = myScanner.nextLine();
System.out.println("Please input an Employee Address");
address = myScanner.nextLine();
emp = new Employee(ID,name,address);
if (pos <= 1 || pos > list.getSize() )
System.out.println("Invalid position\n");
else
list.insertAtPos(emp, pos);
break;
case 4 :
System.out.println("Enter position");
int p = scan.nextInt() ;
if (p < 1 || p > list.getSize() )
System.out.println("Invalid position\n");
else
list.deleteAtPos(p);
break;
case 5 :
list.isEmpty();
case 6 :
System.out.println("Size = "+ list.getSize() +" \n");
break;
case 7:
System.out.println("Enter the name of employee you want to delete:");
myScanner = new Scanner(System.in);
name = myScanner.nextLine();
case 8:
System.out.println("Enter the name of employee you want to search:");
myScanner = new Scanner(System.in);
name = myScanner.nextLine();
default :
System.out.println("Wrong Entry \n ");
break;
}
/* Display List */
list.display();
System.out.println("\nDo you want to continue (Type y or n) \n");
ch = scan.next().charAt(0);
} while (ch == 'Y'|| ch == 'y');
}
}

How Do I Process objects in my custom linked list?

I successfully made a linked list, but now I am having trouble processing it. What methods do I need to add to my FoodList class to be able to process my objects? For example, I need to have the user be able to choose to manually add food objects together so I can print a meal. Also, I can't use any collections classes from the java API. It all must be custom.
public static void main(String[] args) {
FoodList list = new FoodList();
boolean keepGoing = true;
int scanResultInt;
try
{
//I/O stream
FileReader fr = new FileReader("foodlist.txt");
BufferedReader br = new BufferedReader(fr);
Scanner scan = new Scanner(br);
Food hold = new Food();
while(scan.hasNext()){
list.add(hold = new Food());
String str = scan.next();
//str = scan.next();
hold.setName(str);
str = scan.next();
hold.setGroup(str);
int cal = scan.nextInt();
hold.setNumCal(cal);
double percent = scan.nextDouble();
hold.setPercentDV(percent);
list.add(hold);
}
//System.out.println("" + list.toString());
br.close(); //close I/O stream
}
catch(IOException e){
System.err.println("I/O EXCEPTION: " + e.getMessage());
}
Scanner scan2 = new Scanner(System.in);
do {
System.out.println("---------------------------------------------------------");
System.out.println(" Welcome to the Parkland Meal Selector" );
System.out.println("---------------------------------------------------------");
System.out.println("Enter the number of the menu option you would like to select:");
System.out.println(" 1) List food database");
System.out.println(" 2) Create meal by manual selection");
System.out.println(" 3) Create meal by random selection");
System.out.println(" 4) Remove foods high in calories");
System.out.println(" 5) Exit");
scanResultInt = scan2.nextInt();
switch(scanResultInt) {
case 1: {
System.out.println("" + list.toString());
break;
}
case 2: {
System.out.println("Create-A-Meal Menu\n");
System.out.println("Enter the name of a food you would like to add:\n");
String foodWanted = scan2.next();
/*while( != null){
if(foodWanted.equals());
}*/
/*Food tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;*/
}
case 3: {
System.out.println("Create meal by random selection: \n");
break;
}
case 4: {
System.out.println("Remove Food High In Calories: \n");
break;
}
case 5: {
keepGoing = false;
break;
}
}
}
while(keepGoing);
}
Here is my Linked List:
public class FoodList {
// Class fields
private FoodNode head;
private int listCount;
// Private inner class
private class FoodNode
{
public Food f;
public FoodNode next;
public FoodNode(Food f)
{
this.f = f;
this.next = null;
}
}
// Constructor for LinkedList
public FoodList()
{
// Initialize start of the list
head = null;
listCount = 0;
}
// Add method (adds a reservation to the linked list)
public void add(Food f)
{
// Create a new ReservationNode
FoodNode node = new FoodNode(f);
// If this is the first node
if( head == null )
head = node;
else
{
FoodNode tmp = head;
while(tmp.next != null)
tmp = tmp.next;
tmp.next = node;
}
listCount++
}
/*public boolean hasThatFood(String food){
boolean haveThat = false;
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
if (food == f.getName());
haveThat = true;
}
return haveThat;
}*/
/*public boolean hasNext(){
boolean hasNext = false;
if(head != null) {
hasNext = true;
return hasNext;
}
}*/
#Override
public String toString() {
String result = "My Foods:" + '\n';
// Loop through all the reservation nodes
FoodNode tmp;
for(tmp = head; tmp != null; tmp = tmp.next)
{
result += tmp.f;
}
return result;
}
}
And my Food class
public class Food {
private String name;
private String group;
private int numCal;
private double percentDV;
public Food() {//String name, String group, int numCal, double percentDV
/*this.name = name;
this.group = group;
this.numCal = numCal;
this.percentDV = percentDV;*/
name = "";
group = "";
numCal = 0;
percentDV = 0.0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getNumCal() {
return numCal;
}
public void setNumCal(int numCal) {
this.numCal = numCal;
}
public double getPercentDV() {
return percentDV;
}
public void setPercentDV(double percentDV) {
this.percentDV = percentDV;
}
#Override
public String toString() {
return "Food{" +
"name: '" + name + '\'' +
", Food Group: '" + group + '\'' +
", Calories: " + numCal +
", Daily Percent: " + percentDV +
'}';
}
}
I know this is spaghetti code, but this is my last resort. Any help would be appriciated!
To operate on the objects you have to write your custom Iterator. I guess here is nothing criminal to open LinkedList source and look how it works.
Something like this, You can find many resource online,
https://crunchify.com/how-to-implement-a-linkedlist-class-from-scratch-in-java/
Here is one.
public Object getElement(int index)
{
if (index < 0)
return null;
Node Current = null;
if (head != null) {
Current = head.getNext();
for (int i = 0; i < index; i++) {
if (Current.getNext() == null)
return null;
Current = Current.getNext();
}
return Current.getData();
}
return Current;
}
You have implemented some complicated classes. Inner logic of its is not very clear like your issue. So almost any answer will not cover your needs.
If I would you I would try recommend the logic using java core tools (without implementing classes, that implemented in best way LinkedList, ArrayList...). Logic should be converted into some structural solution. For example:
enter point creates and calls your stream service to handle provided input stream;
stream handler should manipulate builder;
builder result have to be collected into composite;
and so on...
If you provide your logic in more structural way you would ask more clear question pointing the issue. Also I believe your question will disappear after this preparation.
Also I would recommend you to get familiar with next GoF patterns: builder, factory method, composite, strategy.

My program just stated acting up and now no matter what I do it always rains insert

I can't figure out what is wrong with my if else statements telling it which statement to run and what is wrong with the insert statement. It keeps going straight back to insert no matter what i type.
import java.util.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.*;
import javax.lang.model.element.*;
public class Node {
public static Node head;
static String data;
static Node next;
static Node q = new Node("", null);
static String inputline;
static int y = 0;
static int count = 0;
static Node current = new Node(q.data, q);
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) {
BuildList();
}
public Node() {
data = "";
next = null;
}
public Node(String x, Node n) {
data = x;
next = n;
}
public static void BuildList() {
try { //match
System.out.println("Please Choose A Command To Execute From The Following List:");
System.out.println("-----------------------------------------------------------");
System.out.println("$insert");
System.out.println("$delete m n");
System.out.println("$print m n");
System.out.println("$line m");
System.out.println("$search String");
System.out.println("$done");
System.out.println(
"Please NOTE: m and n are line number parameters for editing and String is a word");
System.out.println("-----------------------------------------------------------");
inputline = in.readLine();
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
while (!array[0].equals("$done")) //each statement tells it which method to run
{
if (array[0].equals("$insert")) {
Insert();
} else if (array[0].equals("$delete")) {
Delete();
} else if (array[0].equals("$print")) {
Print();
} else if (array[0].equals("$line")) {
Line();
} else if (array[0].equals("$search")) {
Search();
} else {
System.out.println("You have entered an incorrect command");
}
System.out.println("Please enter a command");
inputline = in.readLine();
}
System.out.println("The program is done");
} catch (Exception e) {
System.out.println("Error --" + e.toString());
}
}
public static void Insert() throws IOException {
System.out.println(
"Please Enter The Desired Text (Note: enter $$ when you wish to terminate insert command)");
while (!inputline.equals("$$")) {
inputline = in.readLine();
Node p = new Node(inputline, null);
q.next = p;
q = p;
y++;
}
}
public static void Delete() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head.next;
int lower = Integer.parseInt(array[1]);
int upper = Integer.parseInt(array[2]);
lower--;
if (lower > upper) {
System.out.println("Wrong, first number must be the smaller line number");
} else
for (count = 1; count < y; count++) {
if (lower <= count) {
while (lower <= upper) {
q.next = q.next;
current = q;
lower++;
}
current = q;
break;
} else {
q = q.next;
}
}
}
public static void Print() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head;
if (array.length > 1) {
int lower = Integer.parseInt(array[1]);
int upper = Integer.parseInt(array[2]);
if (lower > upper) {
System.out.println("Wrong, first number must be the smaller line number");
} else {
for (count = 1; count <= y; count++) {
if (lower <= count) {
while (lower <= upper) {
System.out.println(q.data);
q = q.next;
lower++;
}
break;
} else {
q = q.next;
}
}
}
} else {
while (q != null) {
System.out.println(q.data);
q = q.next;
}
}
}
public static void Line() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
q = head.next;
int line_number = Integer.parseInt(array[1]);
for (count = 1; count <= y; count++) {
if (line_number == count) {
System.out.println(q.data);
current = q;
break;
} else {
q = q.next;
}
}
}
public static void Search() {
String[] array = inputline.split(" "); //breaks the command into an array 0,1,2
if (data.contains(array[1])) {
System.out.println(q.data);
} else if (!data.contains(array[1])) {
System.out.println("Word Not Found");
}
}
}
After
System.out.println("Please enter a command");
inputline = in.readLine();
in the while loop, you need to split it into the array again:
array = inputline.split(" ");
otherwise you never change the value of array[0].

Adding a number in between a Range

I have made a program that takes a user's input for start number, end number, and an increment. This is added to a Range (linked-list). I want to add a number that the user inputted to this Range and put the inputted number in between each number.
Main:
public class PDEMain {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a start number: ");
Integer startNum = input.nextInt();
System.out.print("Enter end number: ");
Integer endNum = input.nextInt();
System.out.print("Enter increment: ");
Integer increment = input.nextInt();
Range obj = new Range(startNum, endNum, increment);
obj.display();
System.out.print(" Enter 1 for take:\n "
+ "Enter 2 for drop:\n "
+ "Enter 3 for repeat:\n "
+ "Enter 4 for interpose: ");
Integer number = input.nextInt();
if(number == 1) {
obj.take();
}
if(number == 2) {
obj.drop();
}
if(number == 3) {
obj.repeat();
}
if(number == 4) {
obj.interpose();
}
}
}
Range:
public class Range implements Cloneable {
private Integer data; // holds the data
private Range link; //holds the link
private Range head; //refers to head of linked list
private Integer startValue;
private Integer endValue;
private Scanner input;
public Range(Integer data, Range link) {
this.data = data;
this.link = link;
}
public Range(Integer data, Range link, Range head) {
this.data = data;
this.link = link;
this.head = head;
}
public Range(Integer start, Integer end,Integer increment) {
if(start == null) {
startValue = 0;
}
if(increment == null) {
if(start < end) {
increment++;
} else {
increment--;
}
}
for (int i = start; i <= end; i+= increment) {
addNodeAfter(i);
}
}
public Integer getData() {
return data;
}
public void setData(Integer data) {
this.data = data;
}
public Range getLink() {
return link;
}
public void setLink(Range link) {
this.link = link;
}
public Range getHead() {
return head;
}
public void setHead(Range head) {
this.head = head;
}
I have the following code for this interpose method:
public void interpose() {
System.out.println("What number would you like to interpose? ");
Integer answer = input.nextInt();
Range cursor = head;
for (int i = 0; i <= answer; i++) {
System.out.print(cursor.getData() + " ");
this.link = new Range(answer, this.link);
cursor = cursor.getLink();
}
System.out.print("New Range: ");
display();
modify();
anotherRange();
}
I get a NullPointerException at Integer answer = input.nextInt();
Any tips on why I get this Exception and also if my logic is correct?
Try to add Scanner class into interpose() method like this:
Scanner input = new Scanner(System.in);
Integer answer = input.nextInt();

I'm trying to access a Private Variable from a sub class

Here is the beginning of my code from my sub class RECORD.
class Record {
private int shares;
private int pricePerShare;
// constructor
Record(int sharesNewValue, int pricePerShareNewValue) {
shares = sharesNewValue;
pricePerShare = pricePerShareNewValue;
}
// inspectors
public int getShares() {
return shares;
}
public int getPricePerShare() {
return pricePerShare;
}
// modifiers
public void setShares(int sharesNewValue) {
shares = sharesNewValue;
}
public void setPricePerShare(int pricePerShareNewValue) {
pricePerShare = pricePerShareNewValue;
}
}
And I want to access the value of shares in my main method that is in a different class.I have the RECORD class linked to another subclass named QUEUE. And in my main method, I have a link to QUEUE with this:
class Lab04a {
public static Queue Q = new Queue();
}
Later on in the code, I need to subtract an int value from the SHARES variable in the Record class, but because that is of type Record, I have no clue how to do this!
I'm not sure if I was clear enough when explaining this, should you have any further questions I'll be more than happy to reply.
Thank you.
Due to my inability to coherently state what I'm trying to accomplish in this lab assignment, I'll just post my other two classes in their entirety:
class Queue {
private int count; // number of elements in the queue
private int head; // index of head element, -1 if queue is empty
private int tail; // index of tail element, -1 if queue is empty
private int MAXSIZE = 1; // Physical size of the queue. DO NOT CHANGE!
private Record[] array; // circular array to store the elements of the queue
// constructor
Queue() {
count = 0;
head = -1;
tail = -1;
array = new Record[MAXSIZE];
}
// inspectors
public boolean empty() {
// Returns true if the queue is empty. Otherwise returns false.
return (count != 0);
}
public int size() {
// Returns the number of elements in the queue
return count;
}
public Record front(){
// Returns the head element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count == 0)
return new Record(-1, -1);
else
return array[head];
}
public Record rear(){
// Returns the tail element of the queue if the queue is not empty.
// Otherwise returns a Record with its data parts set to -1.
if (count ==0)
return new Record(-1, -1);
else
return array[tail];
}
public String toString() {
// Returns the elements of the queue
String str = "< ";
int h = head;
for (int i = 0; i < count; i++){
str += "(" + array[h].getShares() + ", " + array[h].getPricePerShare() + ") ";
h = (h+1) % MAXSIZE;
}
str += ">";
return str;
}
// modifiers
public boolean dequeue() {
// Removes the head element of the queue.
if (count == 0)
return false;
if (count == 1) {
count = 0;
head = -1;
tail = -1;
}
if (count > 1){
head = (head + 1) % MAXSIZE;
count--;
}
return true;
}
public void enqueue(Record element) {
// Enqueues element to the tail of the queue.
//if max size is reached, it doubles the size to allow for more values
if (count == MAXSIZE) {
Record[] array2 = new Record[MAXSIZE * 2];
for (int i = 0; i < count; i++) {
array2[i] = array[i];
}//closes for loop
array = array2;
MAXSIZE *= 2;
}
tail = (tail + 1) % MAXSIZE;
array[tail] = element;
if (count == 0)
head = tail;
count++;
}//close enqueue method
}//closes class
And then here is my MAIN parent class:
class Lab04a {
public static Queue Q = new Queue(); // creates global object
public static Record R = Record;
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
int option, buyPrice, buyShares, sellPrice, sellShares, totalShares, totalValues, totalSellPrice;
option = 0;
totalShares = 0;
totalValues = 0;
Queue Q2 = Q;
while (option != 3) {
System.out.print("Enter option (1:buy, 2:sell, 3:quit): ");
option = scan.nextInt();
if (option == 1) {
System.out.print("Enter shares to buy and price per share: ");
buyShares = scan.nextInt();
buyPrice = scan.nextInt();
Record r = new Record(buyShares, buyPrice);
Q.enqueue(r);
totalShares = totalShares + buyShares;
totalValues = totalValues + (buyShares * buyPrice);
}// ends if
if (option == 2) {
System.out.print("Enter shares to sell and price per share: ");
sellShares = scan.nextInt();
sellPrice = scan.nextInt();
totalSellPrice = sellPrice * sellShares;
if (sellShares > totalShares) {
System.out.println("You do not own enough shares for this sale.");
}
for (int i = sellShares; i > 0; ) {
if (sellShares == Q.front().getShares()) {
i -= Q.front().getShares();
Q.dequeue();
}
if (sellShares < Q.front().getShares()){
Record minus;
minus = Q.front() - sellShares;
Q.front().setShares(minus);
Q.front().setShares(Q.front().getShares());
i -= sellShares;
}
}
}// ends if
// Prints content of Queue
System.out.println("Queue: " + Q.toString());
System.out.println("Total Shares: " + totalShares);
System.out.println("Total Shares Value: $" + totalValues);
System.out.println();
}// ends while loop
System.out.println(Q.toString());
}// ends main method
}
If I understand your question, you can add accessor and mutator methods (or getters and setters)
private int shares;
private int pricePerShare;
public int getShares() {
return shares;
}
public void setShares(int shares) {
this.shares = shares;
}
public int getPricePerShare() {
return pricePerShare;
}
public void setPricePerShare(int pricePerShare) {
this.pricePerShare = pricePerShare;
}
Edit
To use it,
Record record = Q.front(); // <-- I assume your Q contains Record(s).
if (record.getShares() >= sellShares) {
record.setShares(record.getShares() - sellShares); // <-- for example
}
Make sure Q.front() is a method that returns a Record.
If that is true, you should be able to use the line
Q.front().setShares(Q.front().getShares()-MINUS_VALUE))

Categories

Resources