I'm trying to make a Queue where you can have different commands for different functions and I used a while loop in order for it to be reusable. But the break; command in the switch case is not working.
Here is the code...
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Scanner;
public class Assign3Besin {
public static void main(String[] args) {
Queue<Person> persons=new LinkedList<Person>();
while(true){
System.out.println(" ");
System.out.println("Functions Available");
System.out.println("A - Display current state of Queue");
System.out.println("B - Enqueue");
System.out.println("C - Dequeue");
System.out.println("D - Sort by Name in Ascension");
System.out.println("E - Sort by Name in Descension");
System.out.println("F - Sort by Age in Ascension");
System.out.println("G - Sort by Age in Descension");
System.out.println("H - Size of the queue");
System.out.println("X - exit program");
System.out.println(" ");
System.out.print("Choose your Function: ");
Scanner scan = new Scanner(System.in);
String a=scan.nextLine();
switch(a){
case "A":
DisplayQ(persons);
break;
case "B":
NQ(persons);
break;
case "C":
DQ(persons);
break;
case "D":
AlphaSortASC(persons);
break;
case "E":
AlphaSortDSC(persons);
break;
case "F":
AgeSortASC(persons);
break;
case "G":
AgeSortDSC(persons);
break;
case "H":
QSize(persons);
break;
case "X":
break;
}
}
}
public static void NQ(Queue<Person> persons) {
Scanner scan= new Scanner(System.in);
System.out.print("How many names are you adding?: ");
int num=Integer.parseInt(scan.nextLine());
System.out.println("Enter "+num+" People's names and Ages");
System.out.println("/LastName, / /FirstName, / /MiddleInitial/Name, / /Age/");
for (int i = 0; i < num; i++) {
System.out.println("Enter full name and age:");
persons.add(new Person(scan.nextLine(),scan.nextLine(),scan.nextLine(),Integer.parseInt(scan.nextLine())));
}
System.out.println("queue now has:"+persons.size()+"Names");
}
public static void DQ(Queue<Person> persons){
Scanner scan= new Scanner(System.in);
System.out.print("How many do you want to remove?: ");
int rmv= Integer.parseInt(scan.nextLine());
for (int i = 0; i < rmv; i++) {
persons.poll();
}
if(persons.isEmpty()){
System.out.println("Queue is empty");
}
}
public static void DisplayQ(Queue<Person> persons) {
for (Person peeps:persons){
System.out.println(peeps);
}
if(persons.isEmpty()){
System.out.println("Queue is empty");
}
}
public static void AlphaSortASC(Queue<Person> persons){
List<Person> lists = (List<Person>) persons;
Collections.sort(lists, new Comparator<Person>() {
public int compare(Person t, Person t1) {
int comp = t.getLname().compareTo(t1.getLname());
if (comp != 0) { // names are different
return comp;
}
return t.getAge() - t1.getAge();
}
});
System.out.println("Queue sorted by name in ascension");
for (Person listy:lists) {
System.out.println(listy);
}
if(persons.isEmpty()){
System.out.println("Queue is empty");
}
}
public static void AlphaSortDSC(Queue<Person> persons){
List<Person> lists = (List<Person>) persons;
Collections.sort(lists, new Comparator<Person>() {
public int compare(Person t1, Person t) {
int comp = t.getLname().compareTo(t1.getLname());
if (comp != 0) { // names are different
return comp;
}
return t.getAge() - t1.getAge();
}
});
System.out.println("Queue sorted by name in descension");
for (Person listy:lists) {
System.out.println(listy);
}
if(persons.isEmpty()){
System.out.println("Queue is empty");
}
}
public static void AgeSortASC(Queue<Person> persons){
List<Person> lists = (List<Person>) persons;
Collections.sort(lists, new Comparator<Person>() {
#Override
public int compare(Person t, Person t1) {
return t.getAge() - t1.getAge();
}
});
System.out.println("Queue sorted by age in ascension");
for (Person listy:lists) {
System.out.println(listy);
}
if(persons.isEmpty()){
System.out.println("Queue is empty");
}
}
public static void AgeSortDSC(Queue<Person> persons){
List<Person> lists = (List<Person>) persons;
Collections.sort(lists, new Comparator<Person>() {
#Override
public int compare(Person t1, Person t) {
return t.getAge() - t1.getAge();
}
});
System.out.println("Queue sorted by age in descension");
for (Person listy:lists) {
System.out.println(listy);
}
if(persons.isEmpty()){
System.out.println("Queue is empty");
}
}
public static void QSize(Queue<Person> persons) {
System.out.println("The queue has "+persons.size()+" Names");
}
}
Whenever I use the code, the break; does not work
Can someone please help meee
The output is just this... over and over and over again
Functions Available
A - Display current state of Queue
B - Enqueue
C - Dequeue
D - Sort by Name in Ascension
E - Sort by Name in Descension
F - Sort by Age in Ascension
G - Sort by Age in Descension
H - Size of the queue
X - exit program
Choose your Function: X
Functions Available
A - Display current state of Queue
B - Enqueue
C - Dequeue
D - Sort by Name in Ascension
E - Sort by Name in Descension
F - Sort by Age in Ascension
G - Sort by Age in Descension
H - Size of the queue
X - exit program
Choose your Function: X
Functions Available
A - Display current state of Queue
B - Enqueue
C - Dequeue
D - Sort by Name in Ascension
E - Sort by Name in Descension
F - Sort by Age in Ascension
G - Sort by Age in Descension
H - Size of the queue
X - exit program
Choose your Function:
java Objects:
class Person {
String Lname; //setting string for last name
String Fname; //setting string for first name
String Mname; //setting string for middle name
int Age; //setting integer for age
public String getLname(){ //get last name
return Lname;
}
public String getFname(){ // get first name
return Fname;
}
public String getMname(){ // get middle name or initial
return Mname;
}
public int getAge(){ // get age
return Age;
}
public void setLname(String Lname){
this.Lname=Lname;
}
public void setFname(String Fname){
this.Fname=Fname;
}
public void setMname(String Mname){
this.Mname=Mname;
}
public void setAge(int Age){
this.Age=Age;
}
public Person (String Lname, String Fname, String Mname, int Age){ // the new object for the nodes
this.Lname=Lname;
this.Fname=Fname;
this.Mname=Mname;
this.Age=Age;
}
#Override
public String toString() {
return "Name:" + Lname + ", " + Fname + " " + Mname + "| Age:" + Age; // this is for the object to be printed into a string
}
}
The break only break the switch and not the loop. To break the loop, you need to label the loop, and use the label to break the loop.
loop: while(true){
switch(a){
case "X": break loop;
}
}
You could use a boolean flag to indicate you want to break out of the while loop:
while(true){
boolean breakWhile = false;
switch(a){
case "X": break loop;
breakWhile = true;
break;
}
if (breakWhile) {
break;
}
}
Related
I am creating in the console a program that adds new students but i wish to check if the max capacity of students is reached or not.
I am learning Java on my own so sorry if my code is not as it should be.
I would appreciate your feedback if you have suggestions.
Main
boolean abort = false;
boolean unlocked = false;
//Student[] students = new Student[School.MAX_studentEntered];
ArrayList<Student> students= new ArrayList<>();
Scanner option = new Scanner(System.in);
while (!abort){ //for as long as the value is not abort the loop will run
System.out.println("Unlock Admin(1) New Student(2) Show Students(3) Statistics (4) ");
System.out.print("Input: ");
int input = option.nextInt();
switch (input){
case 0:{
abort = true;
break;
}
case 1:{
System.out.println("Admin");
unlocked = true;
break;
}
//problem is case 2
case 2: {
System.out.println("Create a student");
int time = 0;
while (time<=School.MAX_studentEntered) {
Scanner st = new Scanner(System.in);
System.out.print("Name: ");
String name = st.nextLine();
System.out.print("Age: ");
int age = st.nextInt();
Student student = new Student();
student.setName(name);
student.setAge(age);
students.add(student);
time++;
if(unlocked){
System.out.print("Create another student? (yes/no): ");
Scanner ans= new Scanner(System.in);
String answer = ans.nextLine();
if (!answer.equals("yes")) {
break;
}
else {
if(time>School.MAX_studentEntered){
System.out.println("You have reached the max capacity!");
break;
}
else {
continue;
}
}
}
if(time>School.MAX_studentEntered){
System.out.println("You have reached the max capacity!");
break;
}
else {
break;
}
}
break;
}
Class Student
public class Student {
String name;
int age;
public Student(){
School.studentEntered++;
}
public void setName(String name){
this.name = name;
}
public void setAge(int age){ //void - save the value
this.age = age;
}
public String getName(){ //return - show the value
return name;
}
public int getAge(){
return age;
}
}
School Class
public class School {
static int studentEntered = 0;
static final int MAX_studentEntered=3;
public School(){
// it is automaticlly created when the class is created
// it does not need a void or return
studentEntered++;
}
}
I expect the program to stop adding new students in the arrayList if the capacity (MAX_studentEntered) is reached and to print an error after the break
I am needing to store 3 different bits of data into a linked list. the first is a name, which i have working, then i need to store the employee number and their occupation. I can't find anything about linking a node to a set of data. any help would be greatly appreciated.
This is the code that runs, TeamMemberTest:
package teammember;
import java.util.*;
import java.util.Scanner;
public class TeamMemberTest {
public static void main(String args[]) {
/* Linked List Declaration */
LinkedList<String> linkedlist = new LinkedList<String>();
Scanner input = new Scanner(System.in);
boolean mainloop = true;
String name;
int employeeNo;
String position;
int choice;
while(true){
System.out.println("Menu");
System.out.print("1. add project \n");
System.out.print("2. display project \n");
System.out.print("3. remove project \n");
System.out.print("4. display all projects \n");
System.out.print("\nEnter your option: ");
choice = input.nextInt();
switch(choice){
case 1:
/*add(String Element) is used for adding
* the elements to the linked list*/
name = Input.getString("name: ");
employeeNo = Input.getInteger("Enter employee number: ");
position = Input.getString("Enter employee position: ");
linkedlist.add(name);
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
break;
case 2:
name = Input.getString("name: ");
if(linkedlist.contains(name)){
System.out.println("LinkedList does contain " + name);
}
break;
case 3:
name = Input.getString("name: ");
linkedlist.remove(name);
System.out.println("LinkedList after deletion of first and last element: " +linkedlist);
break;
case 4:
System.out.println("Linked List Content: " +linkedlist);
break;
default :
System.out.println("This is not a valid option try again.");
break;
}
}
}
}
this code below is TeamMember.java:
package teammember;
public class TeamMember {
//variables
private String name;
private int employeeNo;
private String position;
//the default constant
public TeamMember(){
name = " ";
employeeNo = 0;
position = " ";
}
//overload the constructor
public TeamMember(String name, int employeeNo, String position){
this.name = name;
this.employeeNo = employeeNo;
this.position = position;
}
//the methods
public void setName(String name){
this.name = name;
}
public void setemployeeNo(int employeeNo){
this.employeeNo = employeeNo;
}
public void setPosition(String position){
this.position = position;
}
public String getName(){
return name;
}
public int getemployeeNo(){
return employeeNo;
}
public String getPosition(){
return position;
}
}
and this is the input code:
package teammember;
import java.io.*;
public class Input{
private static BufferedReader input=new BufferedReader(new InputStreamReader(System.in));
public static Character getCharacter(String prompt){
Character value;
System.out.print(prompt);
try{
value=Input.input.readLine().charAt(0);
}
catch(Exception error){
// error condition
value=null;
}
return value;
}
public static Double getDouble(String prompt){
Double value;
System.out.print(prompt);
try{
value=Double.parseDouble(Input.input.readLine());
}
catch(Exception error){
// error condition
throw new NumberFormatException();
}
return value;
}
public static Integer getInteger(String prompt){
Integer value;
System.out.print(prompt);
try{
value=Integer.parseInt(Input.input.readLine());
}
catch(Exception error){
// error condition
throw new NumberFormatException();
}
return value;
}
public static String getString(String prompt){
String string;
System.out.print(prompt);
try{
string=Input.input.readLine();
}
catch(Exception error){
// error condition
string=null;
}
return string;
}
}
Instead of creating a LinkedList of String, you need to create a LinkedList of TeamMember as follows:
LinkedList<TeamMember> linkedlist = new LinkedList<TeamMember>();
Then you need to change the cases accordingly e.g.
choice = input.nextInt();
boolean found;
switch (choice) {
case 1:
name = Input.getString("name: ");
employeeNo = Input.getInteger("Enter employee number: ");
position = Input.getString("Enter employee position: ");
linkedlist.add(new TeamMember(name, employeeNo, position));
break;
case 2:
found = false;
name = Input.getString("name: ");
for (TeamMember teamMember : linkedlist) {
if (teamMember.getName().equalsIgnoreCase(name)) {
System.out.println("Name: " + teamMember.getName() + "Employee No.: "
+ teamMember.getemployeeNo() + "Position: " + teamMember.getPosition());
found = true;
break;
}
}
if (!found) {
System.out.println("The team member was not found.");
}
break;
case 3:
found = false;
name = Input.getString("name: ");
for (TeamMember teamMember : linkedlist) {
if (teamMember.getName().equalsIgnoreCase(name)) {
linkedlist.remove(teamMember);
found = true;
break;
}
}
if (found) {
System.out.println("LinkedList after deletion of " + name + "'s record" + ": " + linkedlist);
} else {
System.out.println("The team member was not found.");
}
break;
case 4:
System.out.println("Linked List Content: " + linkedlist);
break;
default:
System.out.println("This is not a valid option try again.");
break;
}
Make sure to add a toString() method in the class, TeamMember so that you can simply do like System.out.println(an-object-of-TeamMember);. Your IDE can generate the toString() method on the click of a button. Given below is an autogenerated toString() method for your class by eclipse IDE:
#Override
public String toString() {
return "TeamMember [name=" + name + ", employeeNo=" + employeeNo + ", position=" + position + "]";
}
Check this to learn more about toString().
I have been trying most things now but it doesn't seem to work. I want to remove a specific object from an Arraylist if the user enters a specific name. And if not I want the program to print "Can't find dog". I have a getName and toString method in my other class that is working well with all the other options i have in this program, this is the only thing that is not working.
Case 4 is where the removal is supposed to happen. But I also want you to look at Case 3 to compare that Case 3 prints out "can't find dog" no matter what, and case 4 prints out "Cant find dog" as many times as there are objects.
Here is the main method:
ArrayList<Dog> doglist = new ArrayList<Dog>();
Scanner myscan = new Scanner(System.in);
boolean running = true;
while (running) {
System.out.println("\n************************************");
System.out.println("\nVälkommen till Kennelklubben!");
System.out.println("\n************************************");
System.out.println("\n[1] Register new dog");
System.out.println("[2] Print out list");
System.out.println("[3] Increase age");
System.out.println("[4] Remove dog");
System.out.println("[5] Quit program");
System.out.println("\n************************************");
System.out.println("\nChoose: ");
int option = myscan.nextInt();
switch (option) {
case 1:
System.out.println("Write name:");
String name = myscan.next();
System.out.println("Write race:");
String race = myscan.next();
System.out.println("Age:");
int age = myscan.nextInt();
System.out.println("Weight:");
double weight = myscan.nextDouble();
Dog dog = new Dog(name, race, age, weight);
doglist.add(dog);
break;
case 2:
System.out.println("Minimum length of tail:");
double userInput1 = myscan.nextDouble();
for (Dog d : doglist) {
if (d.getTailLength() >= userInput1) {
System.out.println(d.toString());
} else {
System.out.println("Can't find dog");
}
}
break;
case 3:
System.out.println("Name of dog:");
String userInput2 = myscan.next();
for (Dog d : doglist) {
if (d.getName().equals(userInput2)) {
d.increaseAge();
break;
}
}
System.out.println("Can't find dog");
break;
case 4:
System.out.println("Name of dog:");
String userInput3 = myscan.next();
for (Dog d : doglist) {
if (d.getName().equals(userInput3)) {
doglist.remove(d.toString());
} else {
System.out.println("Can't find dog");
}
}
break;
case 5:
running = false;//Avslutar loopen och därmed programmet
System.out.println("Programmet avslutat");
break;
default:
System.out.println("Nu blev det fel, välj mellan [1] [2] [3] [4] [5]");//Felmeddelande om valet är någon annan siffra än de som menyn innehåller
break;
}
}
Here is the other class with my methods
public class Dog
{
private String name;
private String race;
private int age;
private double weight;
private double tailLength;
public Dog (String name, String race, int age, double weight)
{
this.name = name;
this.setRace(race);
this.age = age;
this.weight = weight;
if(race.equals("tax"))
{
this.setTailLength(3.7);
}
else
{
this.setTailLength((age - weight) / 10);
}
}
public String getRace()
{
return race;
}
public void setRace(String race)
{
this.race = race;
}
public double getTailLength()
{
return tailLength;
}
public void setTailLength(double tailLength)
{
this.tailLength = tailLength;
}
public int increaseAge()
{
age++;
return age;
}
public String toString()
{
return name + " " + getRace() +
" " + age + " " + "år" + " " + weight + " " + "kg" + " " + getTailLength();
}
public String getName()
{
return name;
}
}
For clarity's sake, here's what you currently have:
System.out.println("Name of dog:");
String userInput3 = myscan.next();
for(Dog d : doglist)
{
if(d.getName().equals(userInput3))
{
doglist.remove(d.toString());
}
else
{
System.out.println("Can't find dog");
}
}
break;
dogList is a ArrayList<Dog>.
ArrayList.remove()'s documentation states:
Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged.
Here, you're calling remove() with the parameter d.toString(). d is the instance of Dog that you want to remove. d.toString() returns a String.
So dogList.remove(d.toString()) will attempt to remove the String from the list. Obviously this String is not in the list as it is a list of Dog. This String will not be found and nothing will be removed.
As the documentation says, you need to pass the instance that you want to remove. You would need to call doglist.remove(d). This however will cause an error since you can't remove items from a list while you are iterating on it.
Thus, you need to store the Dog instance in a temporary variable and remove it after you have iterated on it.
Something like this would work:
Dog dogToRemove = null;
for (Dog d: dogList) {
if (d.getName().equals(userInput3)) {
dogToRemove = d;
}
}
if (dogToRemove == null) {
System.out.println("Could not find dog with name " + userInput3);
} else {
dogList.remove(dogToRemove);
}
Note that there are other ways to do this, this is just one of them. I encourage you to find alternatives so you understand how this works better.
For case 3 :
Try to add an else and put in your message there
System.out.println("Name of dog:");
String userInput2 = myscan.next();
for (Dog d : doglist) {
if (d.getName().equals(userInput2)) {
d.increaseAge();
break;
}
else {
System.out.println("Can't find dog");
}
}
break;
For case 4 : You can remove by Index
System.out.println("Name of dog:");
String userInput3 = myscan.next();
for (Dog d : doglist) {
if (d.getName().equals(userInput3)) {
doglist.remove(doglist.indexOf(d));
} else {
System.out.println("Can't find dog");
}
}
break;
There is a better way to do this with Java 8.
doglist = doglist.stream().filter(dog -> !dog.getName().equals(userInput3)).collect(toList());
One line of code, easily readable, and no moving parts
And if you want a message if the dog is not found then:
if (doglist.stream().anyMatch(dog -> dog.getName().equals(userInput3)){
doglist = doglist.stream().filter(dog -> !dog.getName().equals(userInput3)).collect(toList());
} else {
System.out.println("Can't find dog");
}
I'm having problems with my Iterator and Deque method and Here's my code:
import java.util.*;
import java.util.Iterator;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public ListIterator<E> iterator = list.listIterator();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public E show(){
return list.peek();
}
public void printQueueElements(){
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public Iterator<E> iterator()
{
return iterator;
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext()
{
return false;
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class Jerald {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
while(true){
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
int numberOfElements = empList.size();
for (int i = 0; i < numberOfElements; i++) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n");
empList.enqueue(emp);
}
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
in case 1, I'm trying to make it retrieve all elements that are in my queue and print it out. Without removing them from there. So basically, instead of using while(hasItems) and poll() which I accomplished and it showed the output that i want, but it deletes everything in the list, so I came up with another approach and used the hasNext method so I used while(empLst.hasNext()) with element() method which only retrieves but does not delete. Unfortunately I have failed on this and have been getting either an empty result after many inputs, or an infinite loop after giving even a single input. How do I fix this? Need help. I think its on my implementation, but I think I have checked already. Anyway I need your opinion on this.
by the way in case 2, im removing the first elementof the linkedlist and showing the first element of the removed linkedlist.
To get rid of your infinite loop problem, remove that outer while(true) loop. Cause infinite loops is exactly what those kinds of loops do, and you don't need it to get the kind of flow you want.
I also introduced a third choice to your menu which clears things up a bit, but I guess that's up to you.
As far as your list problems, fix that "dequeue" method in GenQueue so that it actually does a dequeue (removes the first element in the list), then your case 2 becomes easy.
For printing a list without removing its elements, make use of iterators. I got rid of that ListIterator field in your queue class because you don't need it. In fact, most of the methods you have in that class have already been implemented for you anyways. Take a look at the
List API
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
// return a customer with null values if empty? (up to you)
if (list.isEmpty())
return new Customer("","");
else
return list.remove(0);
}
public E isNotEnd(){
return list.getLast();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty() {
return list.isEmpty();
}
public Iterator<E> iterator() {
return list.iterator();
}
public E removeFirst() {
return list.removeFirst();
}
public E getFirst() {
return list.getFirst();
}
public int size() {
return list.size();
}
public boolean hasNext() {
return false;
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasNext()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
do {
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("3,View queue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try {
choice = sc.nextInt();
switch(choice) {
case 1:
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
break;
case 2:
System.out.println("Dequeued customer: " + empList.dequeue().toString());
break;
case 3:
System.out.println("\nThe customers' names are: \n");
Iterator<Genqueue<Customer>> it = empList.iterator();
while (it.hasNext()) {
Customer emp = it.next();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e) {
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
} while(choice != 0);
}
}
In case 1, after the do-while loop you want to print all the elements in the Queue and keep all the elements.
I see 2 possibilities:
1) Implement in GenQueue a method that iterates the inner list and prints each element without changing anything: public void printQueueElements().
This is the recommended solution.
2) Instead of:
while (empList.hasNext()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
Use:
int numberOfElements = empList.size();
for (int i = 0; i < numberOfElements; i++) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n");
empList.enqueue(emp);
}
This way the queue regains its elements.
The code for case 3 should be:
case 3:
System.out.println("\nThe customers' names are: \n");
Iterator<Customer> it = empList.iterator();
Note the type of the variable "it". Also, the convention is to call an iterator variable "itr" or "iterator".
This is my code:
import java.util.LinkedList;
import java.util.Scanner;
import java.util.InputMismatchException;
import java.util.*;
class Customer {
public String lastName;
public String firstName;
public Customer() {
}
public Customer(String last, String first) {
this.lastName = last;
this.firstName = first;
}
public String toString() {
return firstName + " " + lastName;
}
}
class HourlyCustomer extends Customer {
public double hourlyRate;
public HourlyCustomer(String last, String first) {
super(last, first);
}
}
class GenQueue<E> {
private LinkedList<E> list = new LinkedList<E>();
public void enqueue(E item) {
list.addLast(item);
}
public E dequeue() {
return list.poll();
}
public boolean hasItems() {
return !list.isEmpty();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public E removeFirst(){
return list.removeFirst();
}
public E getFirst(){
return list.getFirst();
}
public int size() {
return list.size();
}
public void addItems(GenQueue<? extends E> q) {
while (q.hasItems()) list.addLast(q.dequeue());
}
}
public class something {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String input1;
String input2;
int choice = 1000;
GenQueue<Customer> empList;
empList = new GenQueue<Customer>();
GenQueue<HourlyCustomer> hList;
hList = new GenQueue<HourlyCustomer>();
while(true){
do{
System.out.println("================");
System.out.println("Queue Operations Menu");
System.out.println("================");
System.out.println("1,Enquene");
System.out.println("2,Dequeue");
System.out.println("0, Quit\n");
System.out.println("Enter Choice:");
try{
choice = sc.nextInt();
switch(choice){
case 1:
do{
System.out.println("\nPlease enter last name: ");
input1 = sc.next();
System.out.println("\nPlease enter first name: ");
input2 = sc.next();
hList.enqueue(new HourlyCustomer(input1, input2));
empList.addItems(hList);
System.out.println("\n"+(input2 + " " + input1) + " is successful queued");
System.out.println("\nDo you still want to enqueue?<1> or do you want to view all in queue?<0> or \nBack to main menu for dequeueing?<menu>: ");
choice = sc.nextInt();
}while (choice != 0);
System.out.println("\nThe customers' names are: \n");
while (empList.hasItems()) {
Customer emp = empList.dequeue();
System.out.println(emp.firstName + " " + emp.lastName + "\n" );
}
break;
case 2:
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nDequeued customer: " +empList.getFirst());
empList.removeFirst();
}
if (empList.isEmpty()) {
System.out.println("The queue is empty!");
}
else
{
System.out.println("\nNext customer in queue: " +empList.getFirst()+"\n");
}
break;
case 0:
System.exit(0);
default:
System.out.println("Invalid choice");
}
}
catch(InputMismatchException e){
System.out.println("Please enter 1-5, 0 to quit");
sc.nextLine();
}
}while(choice != 0);
}
}
}
I want to make a program that accepts queue and then can also dequeue. in case 1 i made the queue successfully, but at case 2, i encountered a certain trouble that I cant figure out that I have to stack overflow it, Im stuck here and I might just be missing out the trivial things on this code. So I need your help. Why does in case 2 my dequeue gets passed an empty list? How do i fix this? Thank you very much!
when you populate your hlist you dequeue all elements from empList and hence your empList will be empty at last.
while (q.hasItems()) list.addLast(q.dequeue());
You can rewrite your addItems method, to just iterate over the elements in the given queue and add them to its own LinkedList.