How Do I Process objects in my custom linked list? - java

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.

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 to Instantiate Connection between Student Class and my LinkedList<E>. Wont grab E.getElement()

I'm working on creating my own LinkedList. My L.L. worked 100% when running simple I/O from command line, but now I have to implement it into my Student class. It adds a Student, displays a student, won't remove Student # Node, in-fact, it won't even read THE ONLY student in the list! All BlueJ tells me is this:
Error(s) found in class
It's some kind of connection logic and for two days I have tried everything I can think of.
Here is my Student, removeStudent(), Class Node, and LinkedList
public class Node
{
private Student item;
private Node node;
private int thisIdx;
private String fullName,firstName,lastName,gender,major,netId;
private int uin,age;
private double gpa;
public Node()
{
this(null,null);
}
public Node(Student stu,Node node)
{
this.item = stu;
this.setNext(node);
thisIdx = totalCount() - 1;
this.setNodeIndex(thisIdx);
}
public int getIndex()
{
return this.thisIdx;
}
public void setNodeIndex(int idx)
{
thisIdx = idx;
}
public void setNext(Node n1)
{
node = n1;
}
public Node getNext()
{
return node;
}
public boolean isEmpty()
{
return ( this == null);
}
public Student display()
{
return this.item;
}
public void setItem(Links data)
{
this.item = data;
}
public Student getItem()
{
return item;
}
}
public class Links<E>
{
private Node start,tail,next;
private int size=0; private int idx; private String item;
private Student student;
/**
* Constructor for objects of class MyLList
*/
public Links()
{
start = new Node();
}
public void addLink(E object)
{
tail = start;
start = new Node(object,tail);
size++;
}
public int totalCount()
{
return size;
}
public Node get(Node node)
{
return node;
}
public void set(Node node)
{
node.setNext(node.getNext());
}
public String emptyMessage()
{
String message = "Your student is not in the student files.\n\n";
return message;
}
public Node getStart()
{
Node curr = start;
return curr;
}
public void clear()
{
Node start = new Node();
size = 0;
}
public void removeLink(Node node) throws NullPointerException
{
try{
Node del,curr,next,prev;
prev = start; curr = start;
while ( curr != node )
{
if ( curr.getNext() == null)
{
throw new NullPointerException();
}else
{
prev = curr;
curr = curr.getNext();
}
}
if ( curr == start)
{
start = start.getNext();
}else
{
prev.setNext(curr.getNext());
curr = curr.getNext();
}
}catch (NullPointerException npe)
{
Lab_12.viewer.append("Breaking in Links" + "\n\n");
}
}
public void sort()
{
Node curr,next,temp,prev;
prev = start;
curr = start;
next = start.getNext();
int move;
Student[] copyToThis = new Student[this.size];
if (this.totalCount() > 1)
{
//copy contents of linked list to array
for (int i=0; i < this.totalCount(); i++)
{
if ( !curr.isEmpty() )
{
Student copyItem = curr.getItem();
copyToThis[i] = copyItem;
prev = curr;
if ( curr.getNext() != null)
{
curr = curr.getNext();
}else
{
prev.setNext(curr.getNext());
}
}
for (int k=0; k < copyToThis.length-1;k++)
{
int tempIdx = k;
if ( copyToThis[k] == null )
{
copyToThis[tempIdx] = copyToThis[k];
while ( k < copyToThis.length-1 )
{
copyToThis[k] = copyToThis[k+1];
copyToThis[k+1] = copyToThis[tempIdx];
tempIdx = k;
k++;
}
}
}
}
//sort array in reverse order -----> LinkedList is FIFO structure
for (int i =0; i < copyToThis.length; i++)
{
Student first = copyToThis[i];
Student tempObject = copyToThis[i];
int tempIndex = i;
for (int k=i; k < copyToThis.length; k++)
{
if (copyToThis[k] != null)
{
move = copyToThis[k].getFullName().compareToIgnoreCase(first.getFullName());
if (move > 0)
{
first = copyToThis[k];
tempIndex = k;
}
}else
{
break;
}
}
if (first == null )
{
break;
}else
{
move = first.getFullName().compareToIgnoreCase(tempObject.getFullName());
if (move > 0 )
{
copyToThis[i] = first;
copyToThis[tempIndex] = tempObject;
tempIndex = i;
}
}
}
//clear list before setting in alphabetical order -----> if not cleared, list will append not replace
this.clear();
for (int i=0; i < copyToThis.length; i++)
{
if ( copyToThis[i] != null)
{
this.addLink(copyToThis[i]);
}
}
}
//test print of array
/*for (int i=0; i < copyToThis.length; i++)
{
Lab_12.viewer.append(i + ") " + copyToThis[i]);
}*/
}
public String displayFirst()
{
Node first = start;
String showFirst = first.getItem().toString();
return showFirst;
}
public void display()
{
String showThisView;
Node prev,curr,next;
prev = start; curr = prev; next = start.getNext();
for (int i=0; i < this.totalCount();i++)
{
if (!curr.isEmpty())
{
showThisView = curr.getItem().toString();
Lab_12.viewer.append(showThisView + "\n\n");
}else
{
prev.setNext(curr.getNext());
curr = curr.getNext();
next = next.getNext();
}
prev = next;
curr = prev;
if (prev.getNext() != null)
{
next = prev.getNext();
}else
{
break;
}
}
}
public String search(String data) throws NullPointerException
{
try{
Node p = start;
while(p!=null)
{
if ( !p.getItem().equals(data) )
{
p = p.getNext();
}else
{
return data;
}
}
}catch (NullPointerException npe)
{
System.out.println("Your item is not in the list\n");
}
}
}
public void removeStudent(Links<Student> studentLinks1)
{
try
{
String toRemove;
int choice;
int counter =0;
toRemove = JOptionPane.showInputDialog(null,"Enter the student last name to be removed:");
String find;
int uin;
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()) )
{
if ( studentLinks1.get(i).getFullName().equalsIgnoreCase(toRemove) )
{
counter++;
}
}
if (counter > 1)
{
viewer.append("You have more than one student with the last name, " + toRemove + ".\n\n");
viewer.append("Students with last name: " + toRemove + "\n\n");
/*
* create array to hold current matching indexes;
*/
for (Node i=studentLinks1.getStart(); i.getNext() !=null; i.setNext(i.getNext()))
{
find = studentLinks1.get(i).getLastName().toString();
if ( studentLinks1.get(i).getLastName().equalsIgnoreCase(toRemove) )
{
uin = studentLinks1.get(i).getUin();
viewer.append("Name: " + studentLinks1.get(i).getFullName().toString() +
"\n\tUIN: " + uin + "\n\n");
}
}
/*
* Get user input for student removal & remove student
*/
int match = 0;
choice = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter the UIN of the student you wish to remove: "));
for (Node i=studentLinks1.getStart(); i.getNext() !=null ; i.setNext(i.getNext()))
{
uin = studentLinks1.get(i).getUin();
if ( choice != uin)
{
match++;
}
if (match == Links.totalCount() )
{
throw new InputMismatchException();
}
}
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()))
{
if ( studentLinks1.get(i).getUin() == choice )
{
String name = studentLinks1.get(i).getFullName().toString();
viewer.append(name + " " + " has been removed from the student file." + "\n\n");
studentLinks1.removeLink(i);
Student.removeStudent();
Student.getStudentCount();
}
}
viewer.append("There is " + Student.getStudentCount() + " student(s) in your student file." + "\n\n");
if ( counter == 1)
{
for (Node i=studentLinks1.getStart(); i.getNext() != null; i.setNext(i.getNext()))
{
if ( studentLinks1.get(i) != null && studentLinks1.get(i).getLastName().equalsIgnoreCase(toRemove) )
{
String firstName = studentLinks1.get(i).getFirstName().toString();
String lastName = studentLinks1.get(i).getLastName().toString();
viewer.append(firstName + " " + lastName + " has been removed from the student file." + "\n\n");
studentLinks1.removeLink(i);
Student.removeStudent();
}
}
viewer.append("There is " + Student.getStudentCount() + " student(s) in your student file." + "\n\n");
}else
{
viewer.append(studentLinks1.emptyMessage());
}
}
}catch (InputMismatchException ime )
{
viewer.append("You entered an incorrect student id.\nPlease re-enter the student id.");
throw ime;
}
}
As you can see in my removeStudent(), I have formatted the for loops to iterate through the L.L. with the nodes themselves. If in LL class, I can perform node.getElement() with results, then why will that not work in my main in Student? I have tried
studentLinks1.get(I).getItem().getElement();
studentLinks1.get(i.getElement())
I am seriously at a loss with this one. Any help is much appreciated!

Tree iterator in Java

I have implemented a code which adds elements in a tree and prints them in increasing order. However my aim is to learn iterators and want to replace the inOrder() function with an iterator function. How can I do this?
import java.util.InputMismatchException;
import java.util.Scanner;
import javax.xml.soap.Node;
class Tree
{
public final int mVal;
public Tree mLeft;
public Tree mRight;
public Node next;
public Tree(int val)
{
mVal = val;
}
public void add(int val)
{
if (val < mVal)
{
if (mLeft == null)
mLeft = new Tree(val);
else
mLeft.add(val);
}
else
{
if (val > mVal)
{
if (mRight == null)
mRight = new Tree(val);
else
mRight.add(val);
}
}
}
public String inOrder()
{
return ((mLeft == null) ? "" : mLeft.inOrder())
+ mVal + " "
+ ((mRight == null) ? "" : mRight.inOrder());
}
public static void main(String[] args)
{
Tree t = new Tree(8);
Scanner scanner = new Scanner(System.in);
boolean continueLoop = true; // determines if more input is needed
for (int i = 1; i < 9; ++i)
{
try // read two numbers and calculate quotient
{
System.out.print("Please enter a random integer : ");
int stackInt = scanner.nextInt();
t.add(Integer.valueOf(stackInt));
} // end try
catch (InputMismatchException inputMismatchException){
System.err.printf("\nException: %s\n", inputMismatchException);
scanner.nextLine(); //discard input so user can try again
System.out.println("You must enter integers. Please try again.\n");
} // end catch
}
System.out.println("Values in order = "+ t.inOrder());
}
}
look at this picture
First Step: if node has a left child, visit left child and do the first step with the child
Second Step: node has no left child (or we visited the left child already), add it to the inorder list
Third Step: first step with right child
i didnt test it
#Override
public String toString() {
return String.valueOf(mVal);
}
public String inOrder(Tree root) {
List<Tree> inOrder = new ArrayList<>();
inOrderRecursively(root, inOrder);
return inOrder.toString();
}
private void inOrderRecursively(Tree Node, List<Tree> inOrder) {
if (Node.mLeft != null) {
inOrderIt(Node.mLeft, inOrder);
}
inOrder.add(Node);
if (Node.mRight != null) {
inOrderIt(Node.mRight, inOrder);
}
}
greetings

java - Queue method help needed

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.

Another issue with LinkedList implementation with another class

Employee Class:
public class Employee
{
String ID;
String Fname;
String Lname;
String City;
String Major;
int GPA;
public Employee()
{
GPA = 0;
}
public void ShowInfo()
{
JOptionPane.showMessageDialog(null, "ID: " + ID + "\nFirst Name: " + Fname + "\nLast Name:" + Lname + "\nCity: " + City + "\nMajor: " + Major + "\nGPA: " + GPA);
}
public void EnterInfo()
{
ID = JOptionPane.showInputDialog("Enter Student ID");
Fname = JOptionPane.showInputDialog("Enter Student First Name");
Lname = JOptionPane.showInputDialog("Enter Student Last Name");
City = JOptionPane.showInputDialog("Enter Student City");
Major = JOptionPane.showInputDialog("Enter Student Major");
String gpa = JOptionPane.showInputDialog("Enter Student GPA");
GPA = Integer.parseInt(gpa);
}
}
}
Linked List:
public class EmployeeList
{
Node first;
Node last;
int count;
public EmployeeList()
{
first = new Node();
first = null;
last = new Node();
last = null;
count = 0;
}
public boolean empty()
{
return first == null;
}
public void add(Employee emp)
{
Node newEmployee = new Node();
newEmployee.e = emp;
newEmployee.e.EnterInfo();
newEmployee.next=null;
if(empty())
{
first=newEmployee;
last=first;
}
else
{
last.next = newEmployee;
last = last.next;
}
count++;
}
public boolean search(String id)
{
Node temp = new Node();
Employee emp = new Employee();
temp = first;
while(temp!=null)
{
emp = temp.e;
if(id.equals(emp.ID))
{
emp.ShowInfo();
return true;
}
temp=temp.next;
}
return false;
}
public boolean delete(String id)
{
Employee emp = new Employee();
if(!empty())
{
if(first.e.ID.equals(id))
{
first=first.next;
return true;
}
else
{
Node previous = new Node();
Node temp = new Node();
previous = first;
temp = first.next;
while(temp!=null)
{
emp = temp.e;
if(id.equals(emp.ID))
{
count--;
previous.next = temp.next;
return true;
}
previous = previous.next;
temp = temp.next;
}
return false;
}
}
return false;
}
public String ALL()
{
String all = new String();
Node temp = new Node();
Employee emp = new Employee();
temp = first;
while(temp!=null)
{
emp = temp.e;
all = all + emp.ID + "-";
temp = temp.next;
}
all = all + "null";
return all;
}
}
I really don't know what's the problem here, If i try to print them all, i keep getting the last entered value.
Node class:
public class Node
{
Employee e = new Employee();
Node next;
}
By searching im not getting any result, just employee ID not found.
EnterInfo method is just for input of the variables (ID,Fname.....)
Any help ? and thanks.
Edit: i know its wrong that way, i should add getters and setter, but this is how the teacher started and told us to start this way.
Your search is failing because you are incorrectly testing for String equality. This line:
if(emp.ID == id)
Tests for object reference equality. It will only work for interned values (which is out of scope for this assignment of yours). You should change it too:
if(id.equals(emp.ID))
Some quick notes on your code:
You are not following best practices in naming. Your variables should
begin with lowercase letters.
You are not following best practice in property scoping. Your class
variables should be private, with appropriate getters/setters
In the beginning of your search method you are unnecessarily creating
a Node instance
Node temp = new Node();
Your are incorrectly testing for String equality in your delete
method.

Categories

Resources