Java hasNext() and element() Implementation in While Loop - java

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".

Related

Out of bounds exception for my quicksort method

When i pass the value to my quick sort method it intialls sets the pivot to the list size but after going through the loop every value gets reset to zero and throws an out of bounds exception.
This is the method in question
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
This is the rest of the program
import java.io.IOException;
import java.util.*;
import java.util.HashMap;
import java.time.LocalDate;
public class BankingSystem {
private int option = 0;
int key;
Double newAccBalance;
String transType;
Double transAmount;
ArrayList<Transaction> list = new ArrayList<>();
HashMap<Integer, Account> accounts = new HashMap<>();
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) throws IOException, InputMismatchException{
BankingSystem bankingSystem = new BankingSystem();
bankingSystem.mainLoop();
}
public void mainLoop() {
option = 0;
while (option != 6) {
display();
option = getKeyboardInteger(keyboard);
if (option == 1) {
createAccount();
} else if (option == 2) {
showAccounts();
} else if (option == 3) {
transaction();
} else if (option == 4) {
deleteAccount();
} else if (option == 5) {
showTransactions();
}
}
}
void display(){
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Main Menu-------------------------------|
---------------------------------------------------------------|
Please select option |
1. Create Account |
2. Display Accounts |
3. Deposit/Withdraw |
4. Delete Account |
5. View Transactions |
6. Exit Program |
---------------------------------------------------------------|
>""");
}
public void createAccount() {
System.out.print("""
---------------------------------------------------------------|
------------------------Create Account Menu--------------------|
---------------------------------------------------------------|
1. Create Account |
2. Return to Main Menu |
""");
while (option == 1 && option !=2) {
System.out.print("Please enter the new account number > ");
int accNum = getKeyboardInteger(keyboard);
System.out.print("Please enter the name of the account holder > ");
String accName = getKeyboardString(keyboard);
System.out.print("Please enter the address of the account holder>> ");
String accAdd = getKeyboardString(keyboard);
System.out.print("Please enter the starting balance: ");
Double accOpBalance = getKeyboardDouble(keyboard);
LocalDate accOpDate = LocalDate.now();
System.out.print("Account open date: " + accOpDate);
Account newAccount = new Account(accNum, accName, accAdd, accOpDate, accOpBalance);
accounts.put(accNum, newAccount);
System.out.print("*Account " + accNum + " added to database* "+ "\n" + ">");
option = getKeyboardInteger(keyboard);
}
}
public void showAccounts() {
option = 0;
while (option == 1 || option != 2){
System.out.print("""
---------------------------------------------------------------|
-----------------------Show Account Menu-----------------------|
---------------------------------------------------------------|
1. View all Accounts |
2. Return to Main Menu |
>""");
option = getKeyboardInteger(keyboard);
for (Map.Entry<Integer, Account> accountEntry : accounts.entrySet()) {
System.out.println("Account key(number) = " + accountEntry.getKey() + accountEntry.getValue());
System.out.println("---------------------------------------------------------------|");
}
}
}
public void deleteAccount(){
int key;
option = 0;
System.out.print("""
---------------------------------------------------------------|
-----------------------Delete Menu-----------------------------|
---------------------------------------------------------------|
1. Delete Account |
2. Main Menu |
>""");
while(option != -1) {
System.out.print("""
Select Account Number
>""");
key = getKeyboardInteger(keyboard);
accounts.remove(key);
option = getKeyboardInteger(keyboard);
}
}
public void transaction(){
option = 0;
while(option != 3){
System.out.println("""
---------------------------------------------------------------|
-----------------------Transaction Menu------------------------|
---------------------------------------------------------------|
Please select the type of transaction:
1. Deposit
2. Withdraw
3. Main Menu""");
option = getKeyboardInteger(keyboard);
switch(option){
case 1 -> {
doDeposit();
break;
}
case 2 -> {
doWithdrawal();
break;
}
}
}
}
public void doWithdrawal(){
transType = "Withdrawal";
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
System.out.print("How Much would you like to withdraw > ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount > getBalance) {
System.out.println("Insufficient funds");
}else{
newAccBalance = getBalance - transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void doDeposit(){
System.out.println("Select Account > ");
key = getKeyboardInteger(keyboard);
transType = "Deposit";
System.out.print("How Much would you like to deposit? ");
transAmount = getKeyboardDouble(keyboard);
Double getBalance = accounts.get(key).getAccOpBalance();
if (transAmount <= 0) {
System.out.print("Please enter a positive value!");
}else {
newAccBalance = getBalance + transAmount;
accounts.get(key).setAccOpBalance(newAccBalance);
accounts.get(key).transList.add(new Transaction(transAmount, transType));
}
}
public void showTransactions() {
option = 0;
key = getKeyboardInteger(keyboard);
list = accounts.get(key).transList;
myQuickSort(list);
while(option != 2) {
System.out.print("""
---------------------------------------------------------------|
-------------------Show Transactions Menu----------------------|
---------------------------------------------------------------|
1.View Transactions
2.Main Menu
>""");
for(int i = 0; i < accounts.get(key).transList.size(); i++){
System.out.print(accounts.get(key).transList.get(i));
}
option = getKeyboardInteger(keyboard);
}
}
public String getKeyboardString(Scanner keyboard){
while (true){
try{
return keyboard.next();
}catch(Exception e){
keyboard.next();
System.out.print("Something went wrong! Please try again" + "\n> ");
}
}
}
public int getKeyboardInteger(Scanner keyboard){
while(true){
try{
return keyboard.nextInt();
}catch(Exception e){
keyboard.next();
System.out.print("Not an option! Please enter a valid option" + "\n> ");
}
}
}
public Double getKeyboardDouble(Scanner Double){
while(true){
try{
return keyboard.nextDouble();
}catch (Exception e){
keyboard.next();
System.out.print("Not an option! Enter an Integer or Decimal value" + "\n>");
}
}
}
public ArrayList<Transaction> myQuickSort(ArrayList<Transaction> list){
ArrayList<Transaction> sorted = new ArrayList<Transaction>();
ArrayList<Transaction> lesser = new ArrayList<Transaction>();
ArrayList<Transaction> greater = new ArrayList<Transaction>();
Transaction pivot = list.get(list.size()-1);
for (int i = 0; i <= list.size()-1; i++){
if(list.get(i).compareTo(pivot) < 0){
lesser.add(list.get(i));
}else{
greater.add(list.get(i));
}
}
lesser = myQuickSort(lesser);
greater = myQuickSort(greater);
lesser.add(pivot);
lesser.addAll(greater);
sorted = lesser;
return sorted;
}
}
import java.time.LocalDate;
import java.util.ArrayList;
public class Account{
private int accNum;
private String accName;
private String accAdd;
private LocalDate accOpDate;
private Double accOpBalance;
public ArrayList<Transaction> transList;
public Account(int accNum, String accName, String accAdd, LocalDate accOpDate, Double accOpBalance){
setAccNum(accNum);
setAccName(accName);
setAccAdd(accAdd);
setAccOpDate(accOpDate);
setAccOpBalance(accOpBalance);
transList = new ArrayList<Transaction>();
}
public void setAccNum(int accNum){
this.accNum = accNum;
}
public int getAccNum(){
return accNum;
}
public void setAccName(String accName){
this.accName = accName;
}
public void setAccAdd(String accAdd){
this.accAdd = accAdd;
}
public void setAccOpDate(LocalDate accOpDate){
this.accOpDate = accOpDate;
}
public void setAccOpBalance(Double accOpBalance){
this.accOpBalance = accOpBalance;
}
public Double getAccOpBalance(){
return accOpBalance;
}
#Override
public String toString() {
return "\n" + "Account Number: " + accNum + "\n" + "Name: " + accName +
"\n" + "Account Holder Address: " + accAdd + "\n" +"Account open date: "
+ accOpDate + "\n" + "Account balance: " + accOpBalance;
}
}
import java.util.ArrayList;
public class Transaction extends ArrayList implements Comparable<Transaction> {
private Double transAmount;
private String transType;
public Transaction(Double transAmount, String transType){
this.transAmount = transAmount;
this.transType = transType;
}
public void setTransAmount(Double transAmount){
this.transAmount = transAmount;
}
public String getTransType(){
return transType;
}
public void setTransType(String transType){
this.transType = transType;
}
public Double getTransAmount(){
return transAmount;
}
#Override
public int compareTo(Transaction compareAcc){
if(this.transAmount < compareAcc.transAmount)
return -1;
else if (compareAcc.transAmount < this.transAmount)
return 1;
return 0;
}
#Override
public String toString() {
return "\n" + "Transaction type: " + transType +
"\n" + "Amount: " + transAmount + "\n";
}
}
Ive tried running through the code step by step in intellij but cant quite figure it out.
Well, I'd like to make this quick and easy to understand. The problem here is that it recurses infinitely. Everytime it reaches the
lesser = myQuickSort(lesser);
line is recurses. And keep in mind that the list parameter this method receives shrinks in size every time it recurses. Because, for example, the first time you give it a list of size 100 then it gets sorted into lesser/greater and then lesser invokes the method again and it recurses again but this time the arraylist given as the parameter is less than the first. Until it reaches a point where the list has pivot = 0 in it and when it's done sorting that it recurses for one final time and attempts to run this line of code.
Transaction pivot = list.get(list.size()-1);
Which attempts to get the Transaction at the -1 index since the list at this point is empty so the size = 0. This causes an ArrayIndexOutOfBoundsException.
This is a very problematic method and also keep in mind that you probably need a base case to stop it from recurring infinitely and also a few improvements in general.
Hope this helps.
Edit: also due to the infinite recursion this method could cause a stackoverflow error

While loop is not stopping/ break command doesn't work JAVA

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

Storing several different bits of data into a linked list

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().

Search arraylist of objects does not work

I have been encountering a specific problem where only the first item in Arraylist is included when it comes to iterating each element in Arraylist (to search/to remove). That means that the second until n-1 iteams won't be found whenever I try to iterate.
Edited: currently improving my code.
You could try the following program. It is perfectly working only when adding the first record of the order: I can remove and search its values. However, when adding the second order: I can not remove and search its values, rather it is not found.
Source code
import java.util.*;
import java.io.*;
public class TestOrders {
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchElementException {
File afile = new File("order.txt");
FileOutputStream outFile = new FileOutputStream("order.txt");
ObjectOutputStream outStream = new ObjectOutputStream(outFile);
FileInputStream inFile = new FileInputStream("order.txt");
ObjectInputStream inStream = new ObjectInputStream(inFile);
//Create an arraylist of order
ArrayList<Order> theorder = new ArrayList<>();
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to Order");
System.out.println("Please choose an option (1-5): ");
int choice = 0;
try {
while (choice != 5) {
//A list of options
System.out.println("\n1. Add a new order: ");
System.out.println("2. Search an order: ");
System.out.println("3. Compute sum of all orders:");
System.out.println("4. Remove an order: ");
System.out.println("5. Exit: ");
//prompt user
System.out.print("Pick a number: ");
if (scan.hasNextInt()) {
choice = scan.nextInt();
}
switch(choice) {
case 1:
addNewOrder(outStream, theorder);
break;
case 2:
searchOrder(outStream, inStream, theorder);
break;
case 3:
computeSum(afile, theorder);
break;
case 4:
removeOrder(outStream, inStream, theorder);
break;
case 5:
System.exit(0);
break;
default:
System.out.println("Please enter from (1-5)");
}
}
} catch (IOException | InputMismatchException ex) {
System.out.println(ex);
} finally {
if (choice == 5) {
scan.close();
outStream.close();
inStream.close();
}
}
}
public static void addNewOrder(ObjectOutputStream outStream, ArrayList<Order> theorder) throws IOException {
Scanner input = new Scanner(System.in);
Order anorder = new Order();
System.out.print("Enter the order ID: ");
anorder.setOrderID(input.nextInt());
input.nextLine();
System.out.print("Enter the customer name: ");
anorder.setCustomerName(input.nextLine());
System.out.print("Enter the order (meal/drink): ");
anorder.setOrderType(input.nextLine());
System.out.print("Enter the order price: ");
anorder.setPrice(input.nextDouble());
if(theorder.size() <= 1000) {
theorder.add(anorder);
outStream.writeObject(anorder);
System.out.println("Order information saved.\n");
} else {
System.out.println("There is not enough space.");
}
}
public static void searchOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) throws FileNotFoundException {
Scanner input = new Scanner(System.in);
Order o = new Order();
System.out.println("Please enter a customer ID: ");
int custID = input.nextInt();
for (Order or : theorder) {
if(or.getOrderID() == custID) {
System.out.println(or.toString());
break;
} else {
System.out.println("No matching record found");
break;
}
}
}
public static void computeSum(File aFile, ArrayList<Order> theorder) throws FileNotFoundException, IOException {
double sum = 0;
for (Order o : theorder) {
sum += o.getPrice();
}
sum = (double) Math.round(sum*100)/100;
System.out.println("The total sum of price for " + theorder.size() + " orders is " + sum);
}
public static void removeOrder(ObjectOutputStream outStream, ObjectInputStream inStream, ArrayList<Order> theorder) {
Iterator<Order> iterator = theorder.iterator();
Scanner input = new Scanner(System.in);
System.out.println("Enter the order ID to remove: ");
int custID = input.nextInt();
while (iterator.hasNext()) {
Order anorder = iterator.next();
if(anorder.getOrderID() == custID) {
theorder.remove(anorder);
System.out.println(anorder.toString());
break;
} else {
System.out.println("Not found\n");
break;
}
}
for (Order o : theorder) {
System.out.println(o.toString());
}
}
}
Order class
import java.util.*;
import java.io.*;
public class Order implements Serializable {
private int orderID;
private String customerName;
private String orderType;
private double price;
public Order() {
}
public Order(int orderID, String customerName, String orderType, double price) {
this.orderID = orderID;
this.customerName = customerName;
this.orderType = orderType;
this.price = price;
}
public int getOrderID() {
return orderID;
}
public void setOrderID(int orderID) {
this.orderID = orderID;
}
public String getCustomerName() {
return this.customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getOrderType() {
return this.orderType;
}
public void setOrderType(String orderType) {
this.orderType = orderType;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String toString() {
return this.orderID + " " + this.customerName + " " + this.orderType + " " + this.price + "\n";
}
}
This part is where I am struggling. I had tried using iterator but it got the same result, second item cannot be iterated/found.
for (Order o : theorder) {
if(o.getOrderID() == orderIDSearch) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
What should I do to fix this problem? is there any way it can be solved?
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
theorder.remove(orderIDSearch);
System.out.println("Order has been successfully removed");
continue;
} else {
System.out.println("Not found ");
break;
}
}
There are several problems here:
First, removal of an element of a collection whilst iterating across the collection requires a different technique than you are using. Generally, modifying a collection in the midst of iteration will result in a ConcurrentModificationException.
Second, are multiple matches expected? If there is at most one match, the continue should be a break.
Third, one would expect the code to continue to following elements when a current element is not a match. That is, the break should be a continue, or better yet, should be removed entirely.
Fourth, its not clear that theorder.remove(orderIDSearch) will do anything, unless the collection type has a remove operation which takes a key value instead of an element value. For basic collection types (List, Set), the call won't do anything.
Here are two rewrites:
If the iterator supports remove:
Iterator<Order> orders = theorder.iterator();
boolean found = false;
while ( !found && orders.hasNext() ) {
if ( orders.next().getOrderID() == orderIDSearch ) {
found = true;
}
}
if ( found ) {
orders.remove();
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
If the iterator does not support remove, then:
boolean found = false;
for ( Order o : theorder ) {
if ( o.getOrderID() == orderIDSearch ) {
found = true;
break;
}
}
if ( found ) {
theorder.remove(orderIDSearch);
System.out.println("Found and removed [ " + orderIDSearch + " ]");
} else {
System.out.println("Not found [ " + orderIDSearch + " ]");
}
Note that this relies on remove accepting a key as the parameter value.
You are breaking the loop in for search in else condition.
Why would you do that.. Remove the else part

Java Queue Program Results to Empty When Dequeueing

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.

Categories