Circular Queue error, display option acting as remove option. [Java OOP] - java

So I have this assignment which is meant to simulate passengers waiting at a boarding gate and we need to create a menu with different options. For it we have to have two classes and a main program and the entire thing is supposed to be based on a circular queue.
While attempting to do the circular queue, I stumbled upon the problem mentioned in the title. When I add items to the queue, once I attempt to display them with the option from the menu, the queue pops the first item, which is not meant to do unless the option delete from the menu is called. Furthermore, if I call the delete and view options, the queue deletes two items. To summarize:
I have no idea why my view option acts as a delete option
Any suggestions as to how to resolve this are appreciated because I've been trying for hours on end, I re-wrote the passenger queue class a few times in different ways, yet still the same and currently I have no idea how to resolve it.
The program is as it follows:
Main:
public class Airport {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
PassengerQueue queue1= new PassengerQueue();
Passenger[] ArrayOfPassenger = new Passenger[20];
Scanner input= new Scanner (System.in);
String optionMenu;
for (int i=0; i<20; i++)
ArrayOfPassenger[i]= new Passenger();
char letter;
do {
System.out.println("Enter display option [A-add passenger, V- view passenger queue, D- delete passenger from queue, S- store passengerQueue data into file, L- load passengerQueue data from file] or 'X' to stop: ");
optionMenu = input.next();
letter = optionMenu.charAt(0);
switch (letter) {
case 'A':
queue1.AddPassenger();
break;
case 'V':
queue1.display();
case 'D':
queue1.removePassenger();
break;
case 'S':
break;
case 'L':
break;
}
} while (letter != 'X');
}
}
Passenger class:
public class Passenger {
private String firstName;
private String surname;
private int secondsInQueue;
Scanner input= new Scanner(System.in);
/**
*
* #return
*/
public String getname(){
return firstName= " "+surname;
}
public void setName (String fName, String sName){
firstName=fName;
surname=sName;
}
public Passenger (){
firstName= "";
surname="";
}
public String toString() {
return firstName + " " + surname;
}
And PassengerQueue class, which is having the issue:
public class PassengerQueue {
Scanner input= new Scanner(System.in);
private Passenger[] qArray =new Passenger [20];
private int first = 0;
private int last = 0;
private int maxStayInQueue;
static final int MAX_QUEUE_SIZE = 20;
public PassengerQueue() {
for (int i = 0;i < 20; i++)
qArray[i]= new Passenger();
}
public void AddPassenger() {
System.out.println("Enter passenger's First Name:");
String FirstName = input.next();
System.out.println("Enter passenger's surname:");
String Surname= input.next();
qArray[last].setName(FirstName, Surname);
last++;
if(last == qArray.length+1){
last = 0;
}
}
public boolean isEmpty() {
return first == 0;
}
public boolean isFull() {
return last == 19;
}
public void removePassenger(){
Passenger x;
x= qArray[first];
qArray[first].setName("","");
first=first+1;
if(first==qArray.length+1)
first=0;
}
public void display() {
System.out.println("The queue: ");
for(int i = first; i < last; i++)
System.out.println(qArray[i]);
}
}

You miss the break; statement after
queue1.display(); in class Airport main method.
So the next case'D' executed.

Related

Java exception running function listEmployee(): java.util.IllegalFormatConversionException

I'm very new to java and I can't figure out what it is I'm doing wrong, it's properly something really basic, I want to be able to add information about employees and then then display/list that data (id, first name, last name, salary, position etc ) using a menu() method.
Everything compiles and adding employee information with addEmployee() seems to work fine but when running listEmployees() I get the exception: java.util.IllegalFormatConversionException.
I have been playing around with it for a bit but I'm not getting anywhere, any help would be greatly appreciated.
import java.util.*;
public class Employee
{
final static int MAX=20;
static int [] idArray= new int[MAX];
static String [] firstnameArray= new String[MAX];
static String [] lastnameArray= new String[MAX];
static int count=0;
public static void add(int id, String fname, String lname)
{
idArray[count] = id;
firstnameArray[count] = fname;
lastnameArray[count] = lname;
++count;
}
public static void addEmployee()
{
Scanner sc=new Scanner(System.in);
for(int i=0; i<idArray.length; i++)
{
System.out.println("Enter your id as an integer");
System.out.print(" (0 to finish): ");
int id = sc.nextInt();
sc.nextLine();
if (id==0)E
return;
System.out.println("Enter your First name");
String fname = sc.nextLine();
System.out.println("Enter your Last name");
String lname = sc.nextLine();
add(id, fname, lname);
}
}
public static void listEmployees()
{
for(int i=0; i<count; ++i)
{
System.out.printf("%-15s %10d \n",idArray[i],firstnameArray[i],lastnameArray[i] );
}
}
public static void printMenu()
{
System.out.println
(
"\n ==Menu==\n" +
"1. Add Employee\n"+
"2. Display Employee\n"+
"3. Quit\n"
);
}
public static void menu()
{
Scanner input = new Scanner(System.in);
int option = 0;
while(option!=3)
{
printMenu();
System.out.println("Please enter your choice");
option = input.nextInt();
switch(option)
{
case 1:
addEmployee();
break;
case 2:
listEmployees();
break;
case 3:
break;
default:
System.out.println("Wrong option");
}
}
}
public static void main(String [] args)
{
menu();
}
}
You are passing a string (lastnameArray[i]) to a numeric format (%10d). You need to first convert the string lastnameArray[i] to an int/long and then pass that value to %10d.
System.out.println(idArray[i] + " " + firstnameArray[i] + " " + lastnameArray[i]);
use this one instaed of your printing statement
The printf function has the wrong arguments passed to it. You should match the format and parameters passed to print them in the same order. Assuming you are passing the correct parameter to be printed, the first parameter should have %d , %s , %s respectively.

Adding to a string array

Working on a program dealing with encapsulation having trouble adding the user input to the array. And most likely there are other problems in here as well. One being the displaying the output when the user enters option 3. Also, I have no idea how to tell the user that they can't add any more to the bag unless they remove an item. I was just gonna work on figuring out adding and display before I even worry about removing.
import java.util.ArrayList;
import java.util.Scanner;
class Bag {
private String[] bag = new String[5];
public String[] bag() {
return bag;
}
public void add(String bag) {
for (int i = 0; i < bag.length(); i++) {
//...
}
return;
}
public void remove(String bag) {
return;
}
void display() {
System.out.println("The contents are: " + this.bag());
}
}
Here is the second class:
import java.util.ArrayList;
import java.util.Scanner;
public class testBag {
public static void main(String[] args) {
cart obj = new cart();
int menu;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList<testcart> cart = new ArrayList<>();
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while (menu != 4) {
switch (menu) {
case 1:
while (choice != 2) {
System.out.println("What do you want to enter: ");
String bag = input.next();
obj.add(bag);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
break;
case 2:
System.out.println("Enter item to Remove: ");
friends.remove(input.next());
break;
case 3:
for (int i = 0; i < obj.bag().length; i++) {
obj.display();
}
break;
}
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All items ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
}
}
Your Bag class has to have a counter for how many bags it already has, and store a new bag in the corresponding position and increment it.
To display the bags you cannot System.out.println the array directly
To remove you need to loop through all the bags and shift them left from the point where you found the one to remove.
Implementing all of this in your Bag class:
public class Bag {
private String[] bag = new String[5];
private int count = 0; //the new count here
public void add(String bagToStore) {
if (count < bag.length){
bag[count] = bagToStore; //store the new bag in the current position
count++; //then increment it
}
}
//the remove has more logic because it has to shift the bags if it removes one,
//not to leave wholes in the array
public void remove(String bagToRemove) {
boolean found = false;
for (int i=0;i < count; ++i){
if (bag[i].equals(bagToRemove)){ //to compare Strings you must use equals
found = true;
}
if (found && count < bag.length){
bag[i] = bag[i+1];
}
}
if (found) count--;
}
void display() {
for (int i = 0; i < count; ++i) //the display has to be done with a for
System.out.println("The contents are: " + bag[i]);
}
}
Your main class would now have to be adjusted as well:
public static void main(String[] args) {
Bag obj = new Bag();
int menu, choice = 0;
Scanner input = new Scanner(System.in);
do {
//only print the menu once, you can use a do while for that
System.out.println(" 1. Add item ");
System.out.println(" 2. Remove item ");
System.out.println(" 3. Display All");
System.out.println(" 4. Exit ");
menu = input.nextInt();
switch (menu) {
case 1:
while (choice != 2) {
System.out.println("What do you want to enter: ");
obj.add(input.next()); //you call add with input.next as well if you want
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
break;
case 2:
System.out.println("What do you want to remove: ");
obj.remove(input.next()); //just call the remove method on Bag
break;
case 3: obj.display(); break; //call the display you already implemented!
}
} while (menu != 4);
}
There are few issues in your implementation of Bag class
You have named String array to store your elements as bad and parameter of add method also as bag, so within add function bag is treated as String rather than String array.
you are not checking the current size of bag before adding elements into bag, you can create a variable named bag and increment it, whenever you add element and decrement it whenever you remove element.
In display method you are printing string array directly instead of elements of array.
I have updated your class by correcting these mistakes
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
class Bag
{
private String bag[] = new String[5];
int size = 0;
Scanner scanner = new Scanner(System.in);
String[] array = new String[2];
public String[] bag(){
return bag;
}
public void add(String item)
{
if( size < bag.length)
{
bag[size] = item;
size++;
}
else
{
System.out.println("Bag is full remove item before new insertion");
}
return;
}
public void remove(String item)
{
}
void display(){
System.out.println("The contents are: " + Arrays.toString(bag));
}
}

How can i use a constructor using JOptionPane to pass objects from my method into a empty array?

I'm having trouble figuring out how to store the objects from the constructor. so far all I get is one object and the remaining are all null. If someone can explain it to me so that a beginner can understand that would be much appreciated.
public class Bookstore
{
/*
Main Class Bookstore to be made modular
*/
public static void main(String args[])
{
Book catalogue[] = new Book[3];
int select;
do
{
select = bookMenu();
switch(select)
{
case 1:
int i =0;
if(catalogue[i] != null)
{
JOptionPane.showMessageDialog(null,"Test");
break;
}
catalogue[i] = addBook();
case 2:
sortBook();
break;
case 3:
searchBook(catalogue);
break;
case 4:
displayBook(catalogue);
break;
case 5:
break;
}
}
while(select != 5);
}
public static int bookMenu()
{
int select;
String menuOptions = "--Book store--\n"
+ "\n1. Add book to catalogue"
+ "\n2.Sort and display books by price"
+ "\n3. Search for a book by title"
+ "\n4. Display all books"
+ "\n\n5. Exit";
do
{
select = Integer.parseInt(JOptionPane.showInputDialog(menuOptions));
}
while(select < 1 || select > 5);
return select;
}
public static Book addBook()
{
int isbn;
String title, author;
Book catalogue = null;
double price;
for(int i=0; i<3;i++)
{
isbn = Integer.parseInt(JOptionPane.showInputDialog
("Enter Book ISBN or: "));
title = JOptionPane.showInputDialog
("Enter Book Title: ");
author = JOptionPane.showInputDialog
("Enter Book Author: ");
price = Double.parseDouble(JOptionPane.showInputDialog
("Enter Book Price: "));
catalogue = new Book(isbn, title, author, price);
}
return catalogue;
}
public static void sortBook()
{
}
public static void searchBook(Book catalogue[])//remain void
{
String searchValue = JOptionPane.showInputDialog("Enter the title of the book you are searching for");
boolean found = true;
for(int i=0; i<catalogue.length && catalogue[i] != null ; i++)
{
if(searchValue.equalsIgnoreCase(catalogue[i].getTitle()))
{
JOptionPane.showMessageDialog(null, "Book details: " + catalogue[i].toString());
found = true;
}
}
if(found == false)
JOptionPane.showMessageDialog(null, "The title does not exist in the collection ");
}
public static void displayBook(Book catalogue[])//remain void
{
String output = "";
for(Book bk:catalogue)
{
output += bk + "\n";
}
JOptionPane.showMessageDialog(null, output);
}
}
So, this is always false...
if(count == max)
You set the values immediately before that statement. Zero never equals ten.
Some IDEs would even point that out to you.
If you want to get a variable that can be used between methods, you need to learn variable scoping.
For example, using a static class variable
private static Book[] books;
private static final int MAX_BOOKS = 10;
private static int count;
public static void main(String[] args) {
books = getBooks();
bookMenu();
}
public static Book[] getBooks() {
if(count == MAX_BOOKS) {
JOptionPane.showMessageDialog(null, "Catalogue full - cannot add any more books");
} else {
for(; count < MAX_BOOKS; count++) {
books[count]= addBook();
}
}
return books;
}
Then, if you want to repeat the menu, use a loop. Don't place it at the end of every method.
Also searchBook(Book) isn't searching for a title. You want to pass a string to the method, not a Book class

How to remove objects from ArrayLists

So i have this homework, to create a java movie program. It should have the add movie (title, actor and date of appearance), show (all the movies added) and remove movie(by movie title) options.
Up till now i was able to create the addMovie(), and showMovie() methods...but i got really stuck ad removeMovies().
Here is the code for the Main.java:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
static Scanner input = new Scanner(System.in);
static ArrayList<Movies> movHolder = new ArrayList<Movies>();
public static void main(String[] args) {
int op = -1;
while (op != 0){
op= menuOption();
switch(op){
case 1:
addMovies();
break;
case 2:
removeMovies();
break;
case 3:
showMovies();
break;
case 0:
System.out.print("\n\nYou have exited the program!");
break;
default:
System.out.println("\nWrong input!");
}
}
}
public static int menuOption(){
int option;
System.out.println("\nMenu\n");
System.out.println("1. Add new movies");
System.out.println("2. Remove movies");
System.out.println("3. Show all movies");
System.out.println("0. Exit program");
System.out.print("\nChoose an option: ");
option = input.nextInt();
return option;
}
public static void addMovies(){
String t, a, d;
input.nextLine();
System.out.println("\n---Adding movies---\n");
System.out.print("Enter title of movie: ");
t = input.nextLine();
System.out.print("Enter actor's name: ");
a = input.nextLine();
System.out.print("Enter date of apearance: ");
d = input.nextLine();
Movies mov = new Movies(t, a, d);
movHolder.add(mov);
}
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
}
public static void showMovies(){
System.out.print("---Showing movie list---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
}
}
And here is the Movies.java with the Movie class:
public class Movies {
private String title;
private String actor;
private String date;
public Movies (String t, String a, String d){
title = t;
actor = a;
date = d;
}
public Movies(){
title = "";
actor = "";
date = "";
}
public String getTitle(){
return title;
}
public String getActor(){
return actor;
}
public String getDate(){
return date;
}
public String toString(){
return "\nTitle: " + title +
"\nActor: " + actor +
"\nRelease date: " + date;
}
}
As you could probably see, i am a very beginner java programmer.
Please, if there is anyway someone could help with the removeMovie() method, i would be very grateful.
Since you have the index of the movie that should be removed (choice - 1) you can use ArrayList.remove(int)
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
movHolder.remove(choice-1);
You can use the remove(int index) method:
public static void removeMovies(){
int choice;
System.out.println("\n---Removing movies by title---\n");
for(int i = 0; i < movHolder.size(); i++){
System.out.println((i+1)+ ".) "+ movHolder.get(i).toString());
}
System.out.print("Enter movie do you want to remove?");
choice = input.nextInt();
// Decrement the index because you're asking the user for a 1 based input.
movHolder.remove(choice - 1)
}
}

How to find size of ArrayList from separate class in Java?

I'm creating a very simple phone directory for a homework assignment but I'm stuck. I've tried looking through similar threads, and while those have been useful they haven't answered my question. I have a class name Directory which has an ArrayList that is compiled from another class called Person. The Person class gathers the information about the contact: First & Last Name, Phone Number and Email addresses of all the contacts. I'm trying to read the ArrayList size from another class: _MainMenu so that if I want to add another contact, the method addNewPerson can be dynamic. I'll include the code for the MainMenu and Directory. Basically I'm trying to avoid having to create a new object for the class Person by hand because I don't know how many contacts the user will have. I hope that makes sense... Sorry if it doesn't. I'll try to clarify as questions undoubtedly come in.
import java.util.Scanner;
public class _MainMenu {
public static Scanner input = new Scanner(System.in);
public static int choice;
public static String firstName = new String();
public static String lastName = "";
public static String phoneNumbers;
public static String emailAddresses;
public static Person pI = new Person ();
public static void main(String[] args) throws Exception
{
Directory d1 = new Directory("myDir.txt");
do
{
printMenu();
selectSubMenu();
if(choice == 1)
{
for(int i = 0; i < d1.getSize(); i++)
d1.addNewPerson(pI);
}
}while(choice != 3);
d1.writeToFile("myDir.txt");
}
public static void printMenu()
{
System.out.printf("%s\n%s\n%s\n%s\n",
"Select The Number Of Your Choice: ",
"1 - Add New Contact",
"2 - Search (Display/Edit/Remove)",
"3 - Exit");
}
public static void selectSubMenu()
{
choice = input.nextInt();
switch(choice)
{
case 1:
addNewContact();
break;
case 2:
// search();
break;
case 3:
break;
default:
System.out.println("Invalid selection. Please try again.");
}
}
public static void addNewContact()
{
System.out.println("Please enter the first name: ");
firstName = input.next();
System.out.println("Please enter the last name: ");
lastName = input.next();
System.out.println("Please enter up to three phone numbers: ");
phoneNumbers += input.next();
System.out.println("Please enter up to three email addresses: ");
emailAddresses += input.next();
}
}
And here's the code for class Directory:
import java.util.ArrayList;
import java.util.Formatter;
import java.io.File;
import java.util.Scanner;
public class Directory {
private ArrayList <Person> directory = new ArrayList <Person>();
public Directory(String name) throws Exception
{
File f = new File(name);
Scanner input;
if(f.exists())
{
input = new Scanner (f);
while(input.hasNext())
{
Person p = new Person();
p.setFname(input.next());
p.setLname(input.next());
int pNumber = input.nextInt();
for (int i=0; i< pNumber; i++)
p.setPhone(input.next());
int eNumber = input.nextInt();
for (int i=0; i< eNumber; i++)
p.setemail(input.next());
directory.add(p);
}
input.close();
}
else
f.createNewFile();
}
public Person find(String fName, String lName)
{
for(int i=0; i<directory.size(); i++)
{
if (directory.get(i).getLname().equals(lName) && directory.get(i).getFname().equals(fName))
return directory.get(i);
}
return null;
}
public void addNewPerson(Person p)
{
directory.add(p);
}
public void writeToFile(String name) throws Exception
{
Formatter inFile = new Formatter(name);
for( int i =0; i< directory.size(); i++){
inFile.format("%s %s %d ", directory.get(i).getFname(),directory.get(i).getLname(),directory.get(i).pNum);
for(int j=0; j<directory.get(i).pNum; j++)
inFile.format("%s ",directory.get(i).getPhones()[j]);
inFile.format("%d ", directory.get(i).eNum);
for(int j=0; j<directory.get(i).eNum; j++)
inFile.format("%s ",directory.get(i).getemails()[j]);
}
inFile.close();
}
}
I understand that the code in MainMenu within the if(choice == 1) statement doesn't work, but I can't think of how to do this. I want to have Person pI to be the dynamic variable so that if the user wants to add another contact, then he selects "Add Contact" and the program will how many contacts are already in the Directory ArrayList and it will add '1' then input that new variable into "d1.addNewPerson(pI)" so that it works something like this: "d1.addNewPerson(d1.size() + 1)"... I don't know if any of that even made sense. Anyway if someone can make sense of it and know how to work the code, I would greatly appreciate it. Thanks.
You are going to have to create a new Person object for each entry.
Person p = new Person();
p.firstname = ...
p.lastname = ..
d1.addNewPerson(p);
and to get the size of the ArrayList, you can try d1.directory.size() since director is a public field. But if possible you should make it private and add a method to Directory
public int getSize()
{
return directory.size();
}
EDIT:
you can modify your code to something like this
if(choice == 1)
{
Person p = new Person();
p.firstname = ...
p.lastname = ..
d1.addNewPerson(pI);
}

Categories