SlideShare a Scribd company logo
1 of 46
Download to read offline
public class FullListException extends Exception {
/**
* Default constructor
*/
public FullListException() {
super();
}
/**
* param message
*/
public FullListException(String message) {
super(message);
}
}
public class NonPositivePriceException extends Exception{
/**
* Default constructor
*/
public NonPositivePriceException() {
super();
}
/**
* param message
*/
public NonPositivePriceException(String message) {
super(message);
}
}
public class MenuItem {
//Attributes
private String name;
private String description;
private double price;
/**
* Default constructor
*/
public MenuItem() {
this.name = "";
this.description = "";
this.price = 0.0;
}
/**
* Parameterized Constructor
* param name
* param description
* param price
*/
public MenuItem(String name, String description, double price) {
this.name = name;
this.description = description;
this.price = price;
}
/**
* return the name
*/
public String getName() {
return name;
}
/**
* param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* return the description
*/
public String getDescription() {
return description;
}
/**
* param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* return the price
*/
public double getPrice() {
return price;
}
/**
* param price the price to set
* throws NonPositivePriceException
*/
public void setPrice(double price) throws NonPositivePriceException {
if(price <= 0)
throw new NonPositivePriceException("Price cannot be set to a non positive value");
this.price = price;
}
/**
* Checks whether this MenuItem has the same attribute values as obj
*/
Override
public boolean equals(Object obj) {
MenuItem item = (MenuItem)obj;
if((this.name.equalsIgnoreCase(item.name)) &&
(this.description.equalsIgnoreCase(item.description)) &&
(this.price == item.price))
return true;
else
return false;
}
Override
public String toString() {
System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description",
"Item Price");
System.out.printf(" %50s", new String(new char[115]).replace('0', '-'));
System.out.printf(" %2s %-25s %-75s %10.2f", "1", this.name, this.description, this.price);
return "";
}
}
public class Menu{
static final int MAX_ITEMS = 50;
//Attributes
private MenuItem[] list;
/**
* Default Constructor
* Construct an instance of the Menu class with no MenuItem objects in it
*
* Postcondition: This Menu has been initialized to an empty list of MenuItems.
*/
public Menu() {
list = new MenuItem[MAX_ITEMS];
}
/**
* Generates a copy of this Menu.
* return The return value is a copy of this Menu.
* Subsequent changes to the copy will not affect the original, nor vice versa.
* Note that the return value is typecast to an Menu before it can be used.
*/
Override
public Object clone() {
Menu clone = new Menu();
if(this.size() > 0) {
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null)
clone.list[i] = this.list[i];
}
}
return clone;
}
/**
* Compare this Menu to another object for equality
* return A return value of true indicates that obj refers to a Menu object with the same
MenuItems in the same order as this Menu.
* Otherwise, the return value is false. If obj is null or it is not a Menu object, then the return
value is false.
*/
Override
public boolean equals(Object obj) {
if((obj == null) || !(obj instanceof Menu)) {
return false;
} else {
Menu menu = (Menu) obj;
if(this.size() != menu.size())
return false;
else {
boolean equal = true;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(!this.list[i].equals(menu.list[i])) {
equal = false;
break;
}
}
return equal;
}
}
}
/**
* Returns the number of MenuItems in this Menu
* Preconditions: This Menu object has been instantiated.
* return : The number of MenuItems in this Menu
*/
public int size() {
int count = 0;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null)
count += 1;
}
return count;
}
/**
* Adds an item at a position
* Preconditions: This Menu object has been instantiated and 1 < position <
items_currently_in_list + 1.
* The number of MenuItem objects in this Menu is less than MAX_ITEMS.
*
* Postcondition:The new MenuItem is now stored at the desired position in the Menu.
* All MenuItems that were originally in positions greater than or equal to position are moved
back one position.
* (Ex: If there are 5 MenuItems in an Menu, positions 1-5, and you insert a new item at position
4,
* the new item will now be at position 4, the item that was at position 4 will be moved to
position 5,
* and the item that was at position 5 will be moved to position 6).
*
* param item : the new MenuItem object to add to this Menu
* param position : the position in the Menu where item will be inserted
*
* throws IllegalArgumentException - Indicates that position is not within the valid range.
* FullListException - Indicates that there is no more room inside of the Menu to store the new
MenuItem object.
*/
public void addItem(MenuItem item, int position) throws FullListException,
IllegalArgumentException{
if(this.list != null) {
if(this.size() == MAX_ITEMS) {
throw new FullListException("No more room inside of the Menu to store the new
MenuItem");
} else if((0 < position) && (position < (MAX_ITEMS + 1))) {
//Shift menuitems one position forward
for(int i = MAX_ITEMS - 1 ; i >= position ; i--) {
this.list[i] = this.list[i - 1];
}
//Add new item at position
this.list[position - 1] = item;
} else {
throw new IllegalArgumentException("Position not within valid range");
}
}
}
/**
* Removes the first menuitem that matches the name
* param name - the name of the Menu to be removed
* throws IllegalArgumentException
*/
public void removeItem(String name) throws IllegalArgumentException {
if(this.list != null) {
boolean found = false;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(!found) {
if(this.list[i].getName().equalsIgnoreCase(name))
found = true;
} else {
//Shift menuitems one position backwards
this.list[i - 1] = this.list[i];
}
}
this.list[MAX_ITEMS - 1] = null;
if(!found)
throw new IllegalArgumentException("Item does not exist in this Menu");
}
}
/**
* Preconditions: This Menu object has been instantiated and 1 < position <
items_currently_in_list.
*
* Postcondition:The MenuItem at the desired position in the Menu has been removed.
* All MenuItems that were originally in positions greater than or equal to position are moved
forward one position.
* (Ex: If there are 5 items in an Menu, positions 1-5, and you remove the item at position 4,
* the item that was at position 5 will be moved to position 4).
*
* param position - the position in the Menu where the MenuItem will be removed from.
*
* throws: IllegalArgumentException Indicates that position is not within the valid range.
*/
public void removeItem(int position) throws IllegalArgumentException {
if(this.list != null) {
if((0 < position) && (position < (MAX_ITEMS + 1))) {
//Shift menuitems one position backwards
for(int i = (position - 1) ; i < (MAX_ITEMS - 1) ; i++) {
this.list[i] = this.list[i + 1];
}
this.list[MAX_ITEMS - 1] = null;
} else
throw new IllegalArgumentException("Position is not within the valid range");
}
}
/**
* Returns MenuItem at the specified position in this Menu object.
* Precondition : This Menu object has been instantiated and 1 < position <
items_currently_in_list
* param position - position of the MenuItem to retrieve
* return
* throws: IllegalArgumentException Indicates that position is not within the valid range.
*/
public MenuItem getItem(int position) throws IllegalArgumentException{
if(this.list != null) {
if((0 < position) && (position < (MAX_ITEMS + 1))) {
return this.list[position - 1];
} else
throw new IllegalArgumentException("Position is not within the valid range");
}
return null;
}
/**
* Return the MenuItem with the given name
* Preconditions:This Menu object has been instantiated
* param name - name of the item to retrieve
* return
* throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
*/
public MenuItem getItemByName(String name) throws IllegalArgumentException{
if(this.list != null) {
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i].getName().equalsIgnoreCase(name))
return this.list[i];
}
}
throw new IllegalArgumentException("Item does not exist in this Menu");
}
/**
* Updates the first MenuItem that matches with name with the given description
* Preconditions:This Menu object has been instantiated
* param name - name of the item
* param desc - new description of the menu with Name name
* throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
*/
public void updateDescription(String name, String newDesc) throws
IllegalArgumentException{
if(this.list != null) {
boolean found = false;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null) {
if(this.list[i].getName().equalsIgnoreCase(name)) {
found = true;
this.list[i].setDescription(newDesc);
break;
}
}
}
if(!found)
throw new IllegalArgumentException("Item does not exist in this Menu");
}
}
/**
* Updates the first MenuItem that matches with name with the given price
* Preconditions:This Menu object has been instantiated
* param name - name of the item
* param price - new price of the menu with Price price
* throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
*/
public void updatePrice(String name, double newPrice) throws NonPositivePriceException,
IllegalArgumentException{
if(this.list != null) {
boolean found = false;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null) {
if(this.list[i].getName().equalsIgnoreCase(name)) {
found = true;
this.list[i].setPrice(newPrice);
break;
}
}
}
if(!found)
throw new IllegalArgumentException("Item does not exist in this Menu");
}
}
/**
* Prints a neatly formatted table of each item in the Menu on its own line with its position
number as shown in the sample output
* Preconditions: This Menu object has been instantiated.
* Postcondition: A neatly formatted table of each MenuItem in the Menu on its own line with its
position number has been displayed to the user.
*/
public void printAllItems() {
this.toString();
}
Override
public String toString() {
if(this.list != null) {
int count = 0;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null) {
if(count == 0) {
System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description",
"Item Price");
System.out.printf(" %50s", new String(new char[115]).replace('0', '-'));
}
count += 1;
System.out.printf(" %2s %-25s %-75s %10.2f", count, this.list[i].getName(),
this.list[i].getDescription(), this.list[i].getPrice());
}
}
}
return "";
}
}
import java.util.Scanner;
public class MenuOperations {
/**
* Clear keyboard buffer
*/
public static void clearBuf(Scanner scanner) {
scanner.nextLine();
}
/**
* Prints the menu
*/
public static void displayMenu() {
System.out.println("  Main menu:");
System.out.println(" A) Add Item " +
" G) Get Item " +
" R) Remove Item " +
" P) Print All Items " +
" S) Size " +
" D) Update description " +
" C) Update price " +
" O) Add to order " +
" I) Remove from order " +
" V) View order " +
" Q) Quit ");
System.out.println(" Select an operation : ");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Menu menu = new Menu(); //Holds the menu
Menu order = new Menu(); //Holds the order
int orderCount = 0; //Counts the number of items in the order
char choice = ' ';
while (true) {
displayMenu();
choice = Character.toUpperCase(scanner.next().charAt(0));
clearBuf(scanner);
switch (choice) {
case 'A': //Add the item to the menu
System.out.println(" Enter the name : ");
String name = scanner.nextLine();
if(name.length() > 25) {
System.out.println("Item name cannot be more than 25.");
} else {
System.out.println(" Enter the description : ");
String desc = scanner.nextLine();
if(desc.length() > 75) {
System.out.println("Item description cannot be more than 75.");
} else {
System.out.println(" Enter the price : ");
double price = scanner.nextDouble();
clearBuf(scanner);
System.out.println(" Enter the position : ");
int position = scanner.nextInt();
clearBuf(scanner);
MenuItem item = new MenuItem(name, desc, price);
try {
menu.addItem(item, position);
System.out.println("Added "" + name + ": " + desc + """ +
" for $" + price + " at position " + position);
} catch (FullListException fle) {
System.out.println(fle.getMessage());
}
}
}
break;
case 'G': //Print out the name, description, and price of the item at the specified position in the
menu
if(menu.size() > 0) {
System.out.println(" Enter position : ");
int position = scanner.nextInt();
clearBuf(scanner);
MenuItem item = menu.getItem(position);
if(item != null)
System.out.println(item);
else
System.out.println("No item found at the specified position");
} else
System.out.println("No items in the menu");
break;
case 'R': //Remove the item with the given name in the menu
if(menu.size() > 0) {
System.out.println(" Enter the Name: ");
name = scanner.nextLine();
try {
menu.removeItem(name);
System.out.println("Removed "" + name + """);
} catch(IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
} else
System.out.println("No item");
break;
case 'P': //Print the list of all items on the menu
menu.printAllItems();
break;
case 'S': //Print the number of items on the menu
System.out.println("There are " + menu.size() + " items in the menu");
break;
case 'D': //Update the description of the named item
if(menu.size() > 0) {
System.out.println(" Enter the name of the item: ");
name = scanner.nextLine();
System.out.println(" Enter the new description: ");
String desc = scanner.nextLine();
if(desc.length() > 75) {
System.out.println("Item description cannot be more than 75.");
} else {
try {
menu.updateDescription(name, desc);
System.out.println("New description set.");
} catch(IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
}
} else
System.out.println("No items in the menu");
break;
case 'C': //Update the price of the named item
if(menu.size() > 0) {
System.out.println(" Enter the name of the item: ");
name = scanner.nextLine();
System.out.println(" Enter the new price: ");
double price = scanner.nextDouble();
try {
menu.updatePrice(name, price);
System.out.println("Changed the price of "" + name + "" to " + price);
} catch(IllegalArgumentException iae) {
System.out.println(iae.getMessage());
} catch(NonPositivePriceException nppe) {
System.out.println(nppe.getMessage());
}
} else
System.out.println("No items in the menu");
break;
case 'O': //Add the item at the specified position in the menu to the order
if(menu.size() > 0) {
System.out.println("Enter position of item to add to order: ");
int position = scanner.nextInt();
clearBuf(scanner);
try {
MenuItem item = menu.getItem(position);
if(item == null)
System.out.println("No menu at position : " + position);
else {
orderCount += 1;
order.addItem(item, orderCount);
System.out.println("Added "" + item.getName() + "" to order");
}
} catch (FullListException fle) {
System.out.println(fle.getMessage());
} catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
} else {
System.out.println("No menu available to add to order");
}
break;
case 'I': //Remove the item at the specified position in the order
if(order.size() > 0) {
System.out.println(" Enter the position : ");
int position = scanner.nextInt();
clearBuf(scanner);
try {
MenuItem item = order.getItem(position);
order.removeItem(position);
orderCount -= 1;
System.out.println("Removed "" + item.getName() + "" from order");
} catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
} else
System.out.println("No items in the order");
break;
case 'V': //Print item in current order
System.out.println("ORDER");
order.printAllItems();
break;
case 'Q':
// Close scanner
scanner.close();
System.exit(0);;
break;
default:
System.out.println("No such operation ");
}
}
}
}
SAMPLE OUTPUT
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
a
Enter the name :
Chicken Parmesan
Enter the description :
Breaded chicken, tomato sauce, and cheese
Enter the price :
8.5
Enter the position :
1
Added "Chicken Parmesan: Breaded chicken, tomato sauce, and cheese" for $8.5 at position 1
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
a
Enter the name :
Hot dog
Enter the description :
Beef sausage in a bun with ketchup
Enter the price :
4.5
Enter the position :
1
Added "Hot dog: Beef sausage in a bun with ketchup" for $4.5 at position 1
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
p
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Hot dog Beef sausage in a bun with ketchup 4.50
2 Chicken Parmesan Breaded chicken, tomato sauce, and cheese
8.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
o
Enter position of item to add to order:
2
Added "Chicken Parmesan" to order
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
v
ORDER
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese
8.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
o
Enter position of item to add to order:
1
Added "Hot dog" to order
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
v
ORDER
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese
8.50
2 Hot dog Beef sausage in a bun with ketchup 4.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
i
Enter the position :
1
Removed "Chicken Parmesan" from order
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
v
ORDER
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Hot dog Beef sausage in a bun with ketchup 4.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
q
Solution
public class FullListException extends Exception {
/**
* Default constructor
*/
public FullListException() {
super();
}
/**
* param message
*/
public FullListException(String message) {
super(message);
}
}
public class NonPositivePriceException extends Exception{
/**
* Default constructor
*/
public NonPositivePriceException() {
super();
}
/**
* param message
*/
public NonPositivePriceException(String message) {
super(message);
}
}
public class MenuItem {
//Attributes
private String name;
private String description;
private double price;
/**
* Default constructor
*/
public MenuItem() {
this.name = "";
this.description = "";
this.price = 0.0;
}
/**
* Parameterized Constructor
* param name
* param description
* param price
*/
public MenuItem(String name, String description, double price) {
this.name = name;
this.description = description;
this.price = price;
}
/**
* return the name
*/
public String getName() {
return name;
}
/**
* param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* return the description
*/
public String getDescription() {
return description;
}
/**
* param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* return the price
*/
public double getPrice() {
return price;
}
/**
* param price the price to set
* throws NonPositivePriceException
*/
public void setPrice(double price) throws NonPositivePriceException {
if(price <= 0)
throw new NonPositivePriceException("Price cannot be set to a non positive value");
this.price = price;
}
/**
* Checks whether this MenuItem has the same attribute values as obj
*/
Override
public boolean equals(Object obj) {
MenuItem item = (MenuItem)obj;
if((this.name.equalsIgnoreCase(item.name)) &&
(this.description.equalsIgnoreCase(item.description)) &&
(this.price == item.price))
return true;
else
return false;
}
Override
public String toString() {
System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description",
"Item Price");
System.out.printf(" %50s", new String(new char[115]).replace('0', '-'));
System.out.printf(" %2s %-25s %-75s %10.2f", "1", this.name, this.description, this.price);
return "";
}
}
public class Menu{
static final int MAX_ITEMS = 50;
//Attributes
private MenuItem[] list;
/**
* Default Constructor
* Construct an instance of the Menu class with no MenuItem objects in it
*
* Postcondition: This Menu has been initialized to an empty list of MenuItems.
*/
public Menu() {
list = new MenuItem[MAX_ITEMS];
}
/**
* Generates a copy of this Menu.
* return The return value is a copy of this Menu.
* Subsequent changes to the copy will not affect the original, nor vice versa.
* Note that the return value is typecast to an Menu before it can be used.
*/
Override
public Object clone() {
Menu clone = new Menu();
if(this.size() > 0) {
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null)
clone.list[i] = this.list[i];
}
}
return clone;
}
/**
* Compare this Menu to another object for equality
* return A return value of true indicates that obj refers to a Menu object with the same
MenuItems in the same order as this Menu.
* Otherwise, the return value is false. If obj is null or it is not a Menu object, then the return
value is false.
*/
Override
public boolean equals(Object obj) {
if((obj == null) || !(obj instanceof Menu)) {
return false;
} else {
Menu menu = (Menu) obj;
if(this.size() != menu.size())
return false;
else {
boolean equal = true;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(!this.list[i].equals(menu.list[i])) {
equal = false;
break;
}
}
return equal;
}
}
}
/**
* Returns the number of MenuItems in this Menu
* Preconditions: This Menu object has been instantiated.
* return : The number of MenuItems in this Menu
*/
public int size() {
int count = 0;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null)
count += 1;
}
return count;
}
/**
* Adds an item at a position
* Preconditions: This Menu object has been instantiated and 1 < position <
items_currently_in_list + 1.
* The number of MenuItem objects in this Menu is less than MAX_ITEMS.
*
* Postcondition:The new MenuItem is now stored at the desired position in the Menu.
* All MenuItems that were originally in positions greater than or equal to position are moved
back one position.
* (Ex: If there are 5 MenuItems in an Menu, positions 1-5, and you insert a new item at position
4,
* the new item will now be at position 4, the item that was at position 4 will be moved to
position 5,
* and the item that was at position 5 will be moved to position 6).
*
* param item : the new MenuItem object to add to this Menu
* param position : the position in the Menu where item will be inserted
*
* throws IllegalArgumentException - Indicates that position is not within the valid range.
* FullListException - Indicates that there is no more room inside of the Menu to store the new
MenuItem object.
*/
public void addItem(MenuItem item, int position) throws FullListException,
IllegalArgumentException{
if(this.list != null) {
if(this.size() == MAX_ITEMS) {
throw new FullListException("No more room inside of the Menu to store the new
MenuItem");
} else if((0 < position) && (position < (MAX_ITEMS + 1))) {
//Shift menuitems one position forward
for(int i = MAX_ITEMS - 1 ; i >= position ; i--) {
this.list[i] = this.list[i - 1];
}
//Add new item at position
this.list[position - 1] = item;
} else {
throw new IllegalArgumentException("Position not within valid range");
}
}
}
/**
* Removes the first menuitem that matches the name
* param name - the name of the Menu to be removed
* throws IllegalArgumentException
*/
public void removeItem(String name) throws IllegalArgumentException {
if(this.list != null) {
boolean found = false;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(!found) {
if(this.list[i].getName().equalsIgnoreCase(name))
found = true;
} else {
//Shift menuitems one position backwards
this.list[i - 1] = this.list[i];
}
}
this.list[MAX_ITEMS - 1] = null;
if(!found)
throw new IllegalArgumentException("Item does not exist in this Menu");
}
}
/**
* Preconditions: This Menu object has been instantiated and 1 < position <
items_currently_in_list.
*
* Postcondition:The MenuItem at the desired position in the Menu has been removed.
* All MenuItems that were originally in positions greater than or equal to position are moved
forward one position.
* (Ex: If there are 5 items in an Menu, positions 1-5, and you remove the item at position 4,
* the item that was at position 5 will be moved to position 4).
*
* param position - the position in the Menu where the MenuItem will be removed from.
*
* throws: IllegalArgumentException Indicates that position is not within the valid range.
*/
public void removeItem(int position) throws IllegalArgumentException {
if(this.list != null) {
if((0 < position) && (position < (MAX_ITEMS + 1))) {
//Shift menuitems one position backwards
for(int i = (position - 1) ; i < (MAX_ITEMS - 1) ; i++) {
this.list[i] = this.list[i + 1];
}
this.list[MAX_ITEMS - 1] = null;
} else
throw new IllegalArgumentException("Position is not within the valid range");
}
}
/**
* Returns MenuItem at the specified position in this Menu object.
* Precondition : This Menu object has been instantiated and 1 < position <
items_currently_in_list
* param position - position of the MenuItem to retrieve
* return
* throws: IllegalArgumentException Indicates that position is not within the valid range.
*/
public MenuItem getItem(int position) throws IllegalArgumentException{
if(this.list != null) {
if((0 < position) && (position < (MAX_ITEMS + 1))) {
return this.list[position - 1];
} else
throw new IllegalArgumentException("Position is not within the valid range");
}
return null;
}
/**
* Return the MenuItem with the given name
* Preconditions:This Menu object has been instantiated
* param name - name of the item to retrieve
* return
* throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
*/
public MenuItem getItemByName(String name) throws IllegalArgumentException{
if(this.list != null) {
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i].getName().equalsIgnoreCase(name))
return this.list[i];
}
}
throw new IllegalArgumentException("Item does not exist in this Menu");
}
/**
* Updates the first MenuItem that matches with name with the given description
* Preconditions:This Menu object has been instantiated
* param name - name of the item
* param desc - new description of the menu with Name name
* throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
*/
public void updateDescription(String name, String newDesc) throws
IllegalArgumentException{
if(this.list != null) {
boolean found = false;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null) {
if(this.list[i].getName().equalsIgnoreCase(name)) {
found = true;
this.list[i].setDescription(newDesc);
break;
}
}
}
if(!found)
throw new IllegalArgumentException("Item does not exist in this Menu");
}
}
/**
* Updates the first MenuItem that matches with name with the given price
* Preconditions:This Menu object has been instantiated
* param name - name of the item
* param price - new price of the menu with Price price
* throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
*/
public void updatePrice(String name, double newPrice) throws NonPositivePriceException,
IllegalArgumentException{
if(this.list != null) {
boolean found = false;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null) {
if(this.list[i].getName().equalsIgnoreCase(name)) {
found = true;
this.list[i].setPrice(newPrice);
break;
}
}
}
if(!found)
throw new IllegalArgumentException("Item does not exist in this Menu");
}
}
/**
* Prints a neatly formatted table of each item in the Menu on its own line with its position
number as shown in the sample output
* Preconditions: This Menu object has been instantiated.
* Postcondition: A neatly formatted table of each MenuItem in the Menu on its own line with its
position number has been displayed to the user.
*/
public void printAllItems() {
this.toString();
}
Override
public String toString() {
if(this.list != null) {
int count = 0;
for(int i = 0 ; i < MAX_ITEMS ; i++) {
if(this.list[i] != null) {
if(count == 0) {
System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description",
"Item Price");
System.out.printf(" %50s", new String(new char[115]).replace('0', '-'));
}
count += 1;
System.out.printf(" %2s %-25s %-75s %10.2f", count, this.list[i].getName(),
this.list[i].getDescription(), this.list[i].getPrice());
}
}
}
return "";
}
}
import java.util.Scanner;
public class MenuOperations {
/**
* Clear keyboard buffer
*/
public static void clearBuf(Scanner scanner) {
scanner.nextLine();
}
/**
* Prints the menu
*/
public static void displayMenu() {
System.out.println("  Main menu:");
System.out.println(" A) Add Item " +
" G) Get Item " +
" R) Remove Item " +
" P) Print All Items " +
" S) Size " +
" D) Update description " +
" C) Update price " +
" O) Add to order " +
" I) Remove from order " +
" V) View order " +
" Q) Quit ");
System.out.println(" Select an operation : ");
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Menu menu = new Menu(); //Holds the menu
Menu order = new Menu(); //Holds the order
int orderCount = 0; //Counts the number of items in the order
char choice = ' ';
while (true) {
displayMenu();
choice = Character.toUpperCase(scanner.next().charAt(0));
clearBuf(scanner);
switch (choice) {
case 'A': //Add the item to the menu
System.out.println(" Enter the name : ");
String name = scanner.nextLine();
if(name.length() > 25) {
System.out.println("Item name cannot be more than 25.");
} else {
System.out.println(" Enter the description : ");
String desc = scanner.nextLine();
if(desc.length() > 75) {
System.out.println("Item description cannot be more than 75.");
} else {
System.out.println(" Enter the price : ");
double price = scanner.nextDouble();
clearBuf(scanner);
System.out.println(" Enter the position : ");
int position = scanner.nextInt();
clearBuf(scanner);
MenuItem item = new MenuItem(name, desc, price);
try {
menu.addItem(item, position);
System.out.println("Added "" + name + ": " + desc + """ +
" for $" + price + " at position " + position);
} catch (FullListException fle) {
System.out.println(fle.getMessage());
}
}
}
break;
case 'G': //Print out the name, description, and price of the item at the specified position in the
menu
if(menu.size() > 0) {
System.out.println(" Enter position : ");
int position = scanner.nextInt();
clearBuf(scanner);
MenuItem item = menu.getItem(position);
if(item != null)
System.out.println(item);
else
System.out.println("No item found at the specified position");
} else
System.out.println("No items in the menu");
break;
case 'R': //Remove the item with the given name in the menu
if(menu.size() > 0) {
System.out.println(" Enter the Name: ");
name = scanner.nextLine();
try {
menu.removeItem(name);
System.out.println("Removed "" + name + """);
} catch(IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
} else
System.out.println("No item");
break;
case 'P': //Print the list of all items on the menu
menu.printAllItems();
break;
case 'S': //Print the number of items on the menu
System.out.println("There are " + menu.size() + " items in the menu");
break;
case 'D': //Update the description of the named item
if(menu.size() > 0) {
System.out.println(" Enter the name of the item: ");
name = scanner.nextLine();
System.out.println(" Enter the new description: ");
String desc = scanner.nextLine();
if(desc.length() > 75) {
System.out.println("Item description cannot be more than 75.");
} else {
try {
menu.updateDescription(name, desc);
System.out.println("New description set.");
} catch(IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
}
} else
System.out.println("No items in the menu");
break;
case 'C': //Update the price of the named item
if(menu.size() > 0) {
System.out.println(" Enter the name of the item: ");
name = scanner.nextLine();
System.out.println(" Enter the new price: ");
double price = scanner.nextDouble();
try {
menu.updatePrice(name, price);
System.out.println("Changed the price of "" + name + "" to " + price);
} catch(IllegalArgumentException iae) {
System.out.println(iae.getMessage());
} catch(NonPositivePriceException nppe) {
System.out.println(nppe.getMessage());
}
} else
System.out.println("No items in the menu");
break;
case 'O': //Add the item at the specified position in the menu to the order
if(menu.size() > 0) {
System.out.println("Enter position of item to add to order: ");
int position = scanner.nextInt();
clearBuf(scanner);
try {
MenuItem item = menu.getItem(position);
if(item == null)
System.out.println("No menu at position : " + position);
else {
orderCount += 1;
order.addItem(item, orderCount);
System.out.println("Added "" + item.getName() + "" to order");
}
} catch (FullListException fle) {
System.out.println(fle.getMessage());
} catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
} else {
System.out.println("No menu available to add to order");
}
break;
case 'I': //Remove the item at the specified position in the order
if(order.size() > 0) {
System.out.println(" Enter the position : ");
int position = scanner.nextInt();
clearBuf(scanner);
try {
MenuItem item = order.getItem(position);
order.removeItem(position);
orderCount -= 1;
System.out.println("Removed "" + item.getName() + "" from order");
} catch (IllegalArgumentException iae) {
System.out.println(iae.getMessage());
}
} else
System.out.println("No items in the order");
break;
case 'V': //Print item in current order
System.out.println("ORDER");
order.printAllItems();
break;
case 'Q':
// Close scanner
scanner.close();
System.exit(0);;
break;
default:
System.out.println("No such operation ");
}
}
}
}
SAMPLE OUTPUT
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
a
Enter the name :
Chicken Parmesan
Enter the description :
Breaded chicken, tomato sauce, and cheese
Enter the price :
8.5
Enter the position :
1
Added "Chicken Parmesan: Breaded chicken, tomato sauce, and cheese" for $8.5 at position 1
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
a
Enter the name :
Hot dog
Enter the description :
Beef sausage in a bun with ketchup
Enter the price :
4.5
Enter the position :
1
Added "Hot dog: Beef sausage in a bun with ketchup" for $4.5 at position 1
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
p
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Hot dog Beef sausage in a bun with ketchup 4.50
2 Chicken Parmesan Breaded chicken, tomato sauce, and cheese
8.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
o
Enter position of item to add to order:
2
Added "Chicken Parmesan" to order
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
v
ORDER
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese
8.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
o
Enter position of item to add to order:
1
Added "Hot dog" to order
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
v
ORDER
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese
8.50
2 Hot dog Beef sausage in a bun with ketchup 4.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
i
Enter the position :
1
Removed "Chicken Parmesan" from order
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
v
ORDER
# Item Name Item Description Item Price
-------------------------------------------------------------------------------------------------------------------
1 Hot dog Beef sausage in a bun with ketchup 4.50
Main menu:
A) Add Item
G) Get Item
R) Remove Item
P) Print All Items
S) Size
D) Update description
C) Update price
O) Add to order
I) Remove from order
V) View order
Q) Quit
Select an operation :
q

More Related Content

Similar to public class FullListException extends Exception { Default .pdf

import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
deepakangel
 
please read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfplease read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdf
aggarwalopticalsco
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdf
seoagam1
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
babitasingh698417
 
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfPlease do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdf
aioils
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
maheshkumar12354
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
ankit11134
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
xlynettalampleyxc
 
we using java dynamicArray package modellinearpub imp.pdf
we using java dynamicArray    package modellinearpub   imp.pdfwe using java dynamicArray    package modellinearpub   imp.pdf
we using java dynamicArray package modellinearpub imp.pdf
adityagupta3310
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
info430661
 
package ADTs public interface CollectionADTltTgt .pdf
package ADTs public interface CollectionADTltTgt      .pdfpackage ADTs public interface CollectionADTltTgt      .pdf
package ADTs public interface CollectionADTltTgt .pdf
syedabdul78662
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
annaelctronics
 
Complete the class ArraySet1java which implements the SetA.pdf
Complete the class ArraySet1java which implements the SetA.pdfComplete the class ArraySet1java which implements the SetA.pdf
Complete the class ArraySet1java which implements the SetA.pdf
abbecindia
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
VictorXUQGloverl
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
accostinternational
 
Array ============ 1. In array, elements can be accessed using .pdf
Array ============ 1. In array, elements can be accessed using .pdfArray ============ 1. In array, elements can be accessed using .pdf
Array ============ 1. In array, elements can be accessed using .pdf
anjaliselectionahd
 

Similar to public class FullListException extends Exception { Default .pdf (20)

import java.util.Iterator; import java.util.NoSuchElementException; .pdf
  import java.util.Iterator; import java.util.NoSuchElementException; .pdf  import java.util.Iterator; import java.util.NoSuchElementException; .pdf
import java.util.Iterator; import java.util.NoSuchElementException; .pdf
 
please read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdfplease read the steps below and it will tell you what we usi.pdf
please read the steps below and it will tell you what we usi.pdf
 
Please help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdfPlease help me to make a programming project I have to sue them today- (1).pdf
Please help me to make a programming project I have to sue them today- (1).pdf
 
STAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdfSTAGE 2 The Methods 65 points Implement all the methods t.pdf
STAGE 2 The Methods 65 points Implement all the methods t.pdf
 
Please do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdfPlease do parts labeled TODO LinkedList.java Replace.pdf
Please do parts labeled TODO LinkedList.java Replace.pdf
 
Implementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdfImplementation The starter code includes List.java. You should not c.pdf
Implementation The starter code includes List.java. You should not c.pdf
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
please read below it will tell you what we are using L.pdf
please read below it will tell you what we are using   L.pdfplease read below it will tell you what we are using   L.pdf
please read below it will tell you what we are using L.pdf
 
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdfClass DiagramIn the Assignment #10, you are given three files Ass.pdf
Class DiagramIn the Assignment #10, you are given three files Ass.pdf
 
we using java dynamicArray package modellinearpub imp.pdf
we using java dynamicArray    package modellinearpub   imp.pdfwe using java dynamicArray    package modellinearpub   imp.pdf
we using java dynamicArray package modellinearpub imp.pdf
 
Given below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdfGiven below is the completed implementation of MyLinkedList class. O.pdf
Given below is the completed implementation of MyLinkedList class. O.pdf
 
package ADTs public interface CollectionADTltTgt .pdf
package ADTs public interface CollectionADTltTgt      .pdfpackage ADTs public interface CollectionADTltTgt      .pdf
package ADTs public interface CollectionADTltTgt .pdf
 
Kotlin 101 Workshop
Kotlin 101 WorkshopKotlin 101 Workshop
Kotlin 101 Workshop
 
Hi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdfHi,I have added the methods and main class as per your requirement.pdf
Hi,I have added the methods and main class as per your requirement.pdf
 
Write a program to find the number of comparisons using the binary se.docx
 Write a program to find the number of comparisons using the binary se.docx Write a program to find the number of comparisons using the binary se.docx
Write a program to find the number of comparisons using the binary se.docx
 
Complete the class ArraySet1java which implements the SetA.pdf
Complete the class ArraySet1java which implements the SetA.pdfComplete the class ArraySet1java which implements the SetA.pdf
Complete the class ArraySet1java which implements the SetA.pdf
 
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
Java Foundations StackADT-java ---  - Defines the interface to a stack.docxJava Foundations StackADT-java ---  - Defines the interface to a stack.docx
Java Foundations StackADT-java --- - Defines the interface to a stack.docx
 
public class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdfpublic class MyLinkedListltE extends ComparableltEgtg.pdf
public class MyLinkedListltE extends ComparableltEgtg.pdf
 
Array ============ 1. In array, elements can be accessed using .pdf
Array ============ 1. In array, elements can be accessed using .pdfArray ============ 1. In array, elements can be accessed using .pdf
Array ============ 1. In array, elements can be accessed using .pdf
 
Posfix
PosfixPosfix
Posfix
 

More from annapurnnatextailes

Types of Fluoride Additives Community water syst.pdf
                     Types of Fluoride Additives  Community water syst.pdf                     Types of Fluoride Additives  Community water syst.pdf
Types of Fluoride Additives Community water syst.pdf
annapurnnatextailes
 
The theory, or doctrine, of forms (also called th.pdf
                     The theory, or doctrine, of forms (also called th.pdf                     The theory, or doctrine, of forms (also called th.pdf
The theory, or doctrine, of forms (also called th.pdf
annapurnnatextailes
 
Moles of EDTA added initially to the solution = (.pdf
                     Moles of EDTA added initially to the solution = (.pdf                     Moles of EDTA added initially to the solution = (.pdf
Moles of EDTA added initially to the solution = (.pdf
annapurnnatextailes
 
If I am reading the question right, this would be.pdf
                     If I am reading the question right, this would be.pdf                     If I am reading the question right, this would be.pdf
If I am reading the question right, this would be.pdf
annapurnnatextailes
 
Thermostability                          is the quality of a subst.pdf
Thermostability                          is the quality of a subst.pdfThermostability                          is the quality of a subst.pdf
Thermostability                          is the quality of a subst.pdf
annapurnnatextailes
 
WAN is a wide area network in which two or more computer or other de.pdf
WAN is a wide area network in which two or more computer or other de.pdfWAN is a wide area network in which two or more computer or other de.pdf
WAN is a wide area network in which two or more computer or other de.pdf
annapurnnatextailes
 
The most important characteristics that comprise the software qualit.pdf
The most important characteristics that comprise the software qualit.pdfThe most important characteristics that comprise the software qualit.pdf
The most important characteristics that comprise the software qualit.pdf
annapurnnatextailes
 

More from annapurnnatextailes (20)

Xs mothers fourth child was X. the question its.pdf
                     Xs mothers fourth child was X. the question its.pdf                     Xs mothers fourth child was X. the question its.pdf
Xs mothers fourth child was X. the question its.pdf
 
Types of Fluoride Additives Community water syst.pdf
                     Types of Fluoride Additives  Community water syst.pdf                     Types of Fluoride Additives  Community water syst.pdf
Types of Fluoride Additives Community water syst.pdf
 
This is blue because ion absorbs yellow radiation.pdf
                     This is blue because ion absorbs yellow radiation.pdf                     This is blue because ion absorbs yellow radiation.pdf
This is blue because ion absorbs yellow radiation.pdf
 
The theory, or doctrine, of forms (also called th.pdf
                     The theory, or doctrine, of forms (also called th.pdf                     The theory, or doctrine, of forms (also called th.pdf
The theory, or doctrine, of forms (also called th.pdf
 
The left ring would undergo nitration more easily.pdf
                     The left ring would undergo nitration more easily.pdf                     The left ring would undergo nitration more easily.pdf
The left ring would undergo nitration more easily.pdf
 
sol a. Im guessing that they are used to react .pdf
                     sol a. Im guessing that they are used to react .pdf                     sol a. Im guessing that they are used to react .pdf
sol a. Im guessing that they are used to react .pdf
 
Resonance structures demonstrate one of the weakn.pdf
                     Resonance structures demonstrate one of the weakn.pdf                     Resonance structures demonstrate one of the weakn.pdf
Resonance structures demonstrate one of the weakn.pdf
 
no. of moles = massmolecular weight here no mass.pdf
                     no. of moles = massmolecular weight here no mass.pdf                     no. of moles = massmolecular weight here no mass.pdf
no. of moles = massmolecular weight here no mass.pdf
 
Moles of EDTA added initially to the solution = (.pdf
                     Moles of EDTA added initially to the solution = (.pdf                     Moles of EDTA added initially to the solution = (.pdf
Moles of EDTA added initially to the solution = (.pdf
 
IV Water has a high boiling compared to H2S. .pdf
                     IV Water has a high boiling compared to H2S.    .pdf                     IV Water has a high boiling compared to H2S.    .pdf
IV Water has a high boiling compared to H2S. .pdf
 
it is NO2 addition in meta position giving 1,3 di.pdf
                     it is NO2 addition in meta position giving 1,3 di.pdf                     it is NO2 addition in meta position giving 1,3 di.pdf
it is NO2 addition in meta position giving 1,3 di.pdf
 
in saturn weight is 1.064 times that of the earth.pdf
                     in saturn weight is 1.064 times that of the earth.pdf                     in saturn weight is 1.064 times that of the earth.pdf
in saturn weight is 1.064 times that of the earth.pdf
 
If I am reading the question right, this would be.pdf
                     If I am reading the question right, this would be.pdf                     If I am reading the question right, this would be.pdf
If I am reading the question right, this would be.pdf
 
Which of the following are true statements about serial interfaces.pdf
Which of the following are true statements about serial interfaces.pdfWhich of the following are true statements about serial interfaces.pdf
Which of the following are true statements about serial interfaces.pdf
 
Thermostability                          is the quality of a subst.pdf
Thermostability                          is the quality of a subst.pdfThermostability                          is the quality of a subst.pdf
Thermostability                          is the quality of a subst.pdf
 
VictimizedSolutionVictimized.pdf
VictimizedSolutionVictimized.pdfVictimizedSolutionVictimized.pdf
VictimizedSolutionVictimized.pdf
 
True,Design activities for high risk system interfaces might come up.pdf
True,Design activities for high risk system interfaces might come up.pdfTrue,Design activities for high risk system interfaces might come up.pdf
True,Design activities for high risk system interfaces might come up.pdf
 
WAN is a wide area network in which two or more computer or other de.pdf
WAN is a wide area network in which two or more computer or other de.pdfWAN is a wide area network in which two or more computer or other de.pdf
WAN is a wide area network in which two or more computer or other de.pdf
 
The most important characteristics that comprise the software qualit.pdf
The most important characteristics that comprise the software qualit.pdfThe most important characteristics that comprise the software qualit.pdf
The most important characteristics that comprise the software qualit.pdf
 
The electronic configuration of H is 1s1 It has one valence electr.pdf
The electronic configuration of H is 1s1 It has one valence electr.pdfThe electronic configuration of H is 1s1 It has one valence electr.pdf
The electronic configuration of H is 1s1 It has one valence electr.pdf
 

Recently uploaded

The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 

Recently uploaded (20)

General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

public class FullListException extends Exception { Default .pdf

  • 1. public class FullListException extends Exception { /** * Default constructor */ public FullListException() { super(); } /** * param message */ public FullListException(String message) { super(message); } } public class NonPositivePriceException extends Exception{ /** * Default constructor */ public NonPositivePriceException() { super(); } /** * param message */ public NonPositivePriceException(String message) { super(message); } } public class MenuItem { //Attributes private String name; private String description; private double price; /**
  • 2. * Default constructor */ public MenuItem() { this.name = ""; this.description = ""; this.price = 0.0; } /** * Parameterized Constructor * param name * param description * param price */ public MenuItem(String name, String description, double price) { this.name = name; this.description = description; this.price = price; } /** * return the name */ public String getName() { return name; } /** * param name the name to set */ public void setName(String name) { this.name = name; } /** * return the description */ public String getDescription() { return description; }
  • 3. /** * param description the description to set */ public void setDescription(String description) { this.description = description; } /** * return the price */ public double getPrice() { return price; } /** * param price the price to set * throws NonPositivePriceException */ public void setPrice(double price) throws NonPositivePriceException { if(price <= 0) throw new NonPositivePriceException("Price cannot be set to a non positive value"); this.price = price; } /** * Checks whether this MenuItem has the same attribute values as obj */ Override public boolean equals(Object obj) { MenuItem item = (MenuItem)obj; if((this.name.equalsIgnoreCase(item.name)) && (this.description.equalsIgnoreCase(item.description)) && (this.price == item.price)) return true; else return false; } Override
  • 4. public String toString() { System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description", "Item Price"); System.out.printf(" %50s", new String(new char[115]).replace('0', '-')); System.out.printf(" %2s %-25s %-75s %10.2f", "1", this.name, this.description, this.price); return ""; } } public class Menu{ static final int MAX_ITEMS = 50; //Attributes private MenuItem[] list; /** * Default Constructor * Construct an instance of the Menu class with no MenuItem objects in it * * Postcondition: This Menu has been initialized to an empty list of MenuItems. */ public Menu() { list = new MenuItem[MAX_ITEMS]; } /** * Generates a copy of this Menu. * return The return value is a copy of this Menu. * Subsequent changes to the copy will not affect the original, nor vice versa. * Note that the return value is typecast to an Menu before it can be used. */ Override public Object clone() { Menu clone = new Menu(); if(this.size() > 0) { for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null)
  • 5. clone.list[i] = this.list[i]; } } return clone; } /** * Compare this Menu to another object for equality * return A return value of true indicates that obj refers to a Menu object with the same MenuItems in the same order as this Menu. * Otherwise, the return value is false. If obj is null or it is not a Menu object, then the return value is false. */ Override public boolean equals(Object obj) { if((obj == null) || !(obj instanceof Menu)) { return false; } else { Menu menu = (Menu) obj; if(this.size() != menu.size()) return false; else { boolean equal = true; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(!this.list[i].equals(menu.list[i])) { equal = false; break; } } return equal; } }
  • 6. } /** * Returns the number of MenuItems in this Menu * Preconditions: This Menu object has been instantiated. * return : The number of MenuItems in this Menu */ public int size() { int count = 0; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) count += 1; } return count; } /** * Adds an item at a position * Preconditions: This Menu object has been instantiated and 1 < position < items_currently_in_list + 1. * The number of MenuItem objects in this Menu is less than MAX_ITEMS. * * Postcondition:The new MenuItem is now stored at the desired position in the Menu. * All MenuItems that were originally in positions greater than or equal to position are moved back one position. * (Ex: If there are 5 MenuItems in an Menu, positions 1-5, and you insert a new item at position 4, * the new item will now be at position 4, the item that was at position 4 will be moved to position 5, * and the item that was at position 5 will be moved to position 6). * * param item : the new MenuItem object to add to this Menu * param position : the position in the Menu where item will be inserted *
  • 7. * throws IllegalArgumentException - Indicates that position is not within the valid range. * FullListException - Indicates that there is no more room inside of the Menu to store the new MenuItem object. */ public void addItem(MenuItem item, int position) throws FullListException, IllegalArgumentException{ if(this.list != null) { if(this.size() == MAX_ITEMS) { throw new FullListException("No more room inside of the Menu to store the new MenuItem"); } else if((0 < position) && (position < (MAX_ITEMS + 1))) { //Shift menuitems one position forward for(int i = MAX_ITEMS - 1 ; i >= position ; i--) { this.list[i] = this.list[i - 1]; } //Add new item at position this.list[position - 1] = item; } else { throw new IllegalArgumentException("Position not within valid range"); } } } /** * Removes the first menuitem that matches the name * param name - the name of the Menu to be removed * throws IllegalArgumentException */ public void removeItem(String name) throws IllegalArgumentException { if(this.list != null) { boolean found = false; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(!found) { if(this.list[i].getName().equalsIgnoreCase(name)) found = true;
  • 8. } else { //Shift menuitems one position backwards this.list[i - 1] = this.list[i]; } } this.list[MAX_ITEMS - 1] = null; if(!found) throw new IllegalArgumentException("Item does not exist in this Menu"); } } /** * Preconditions: This Menu object has been instantiated and 1 < position < items_currently_in_list. * * Postcondition:The MenuItem at the desired position in the Menu has been removed. * All MenuItems that were originally in positions greater than or equal to position are moved forward one position. * (Ex: If there are 5 items in an Menu, positions 1-5, and you remove the item at position 4, * the item that was at position 5 will be moved to position 4). * * param position - the position in the Menu where the MenuItem will be removed from. * * throws: IllegalArgumentException Indicates that position is not within the valid range. */ public void removeItem(int position) throws IllegalArgumentException { if(this.list != null) { if((0 < position) && (position < (MAX_ITEMS + 1))) { //Shift menuitems one position backwards for(int i = (position - 1) ; i < (MAX_ITEMS - 1) ; i++) { this.list[i] = this.list[i + 1]; } this.list[MAX_ITEMS - 1] = null; } else throw new IllegalArgumentException("Position is not within the valid range");
  • 9. } } /** * Returns MenuItem at the specified position in this Menu object. * Precondition : This Menu object has been instantiated and 1 < position < items_currently_in_list * param position - position of the MenuItem to retrieve * return * throws: IllegalArgumentException Indicates that position is not within the valid range. */ public MenuItem getItem(int position) throws IllegalArgumentException{ if(this.list != null) { if((0 < position) && (position < (MAX_ITEMS + 1))) { return this.list[position - 1]; } else throw new IllegalArgumentException("Position is not within the valid range"); } return null; } /** * Return the MenuItem with the given name * Preconditions:This Menu object has been instantiated * param name - name of the item to retrieve * return * throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu */ public MenuItem getItemByName(String name) throws IllegalArgumentException{ if(this.list != null) { for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i].getName().equalsIgnoreCase(name)) return this.list[i]; } }
  • 10. throw new IllegalArgumentException("Item does not exist in this Menu"); } /** * Updates the first MenuItem that matches with name with the given description * Preconditions:This Menu object has been instantiated * param name - name of the item * param desc - new description of the menu with Name name * throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu */ public void updateDescription(String name, String newDesc) throws IllegalArgumentException{ if(this.list != null) { boolean found = false; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) { if(this.list[i].getName().equalsIgnoreCase(name)) { found = true; this.list[i].setDescription(newDesc); break; } } } if(!found) throw new IllegalArgumentException("Item does not exist in this Menu"); } } /** * Updates the first MenuItem that matches with name with the given price * Preconditions:This Menu object has been instantiated * param name - name of the item * param price - new price of the menu with Price price
  • 11. * throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu */ public void updatePrice(String name, double newPrice) throws NonPositivePriceException, IllegalArgumentException{ if(this.list != null) { boolean found = false; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) { if(this.list[i].getName().equalsIgnoreCase(name)) { found = true; this.list[i].setPrice(newPrice); break; } } } if(!found) throw new IllegalArgumentException("Item does not exist in this Menu"); } } /** * Prints a neatly formatted table of each item in the Menu on its own line with its position number as shown in the sample output * Preconditions: This Menu object has been instantiated. * Postcondition: A neatly formatted table of each MenuItem in the Menu on its own line with its position number has been displayed to the user. */ public void printAllItems() { this.toString(); } Override public String toString() { if(this.list != null) {
  • 12. int count = 0; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) { if(count == 0) { System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description", "Item Price"); System.out.printf(" %50s", new String(new char[115]).replace('0', '-')); } count += 1; System.out.printf(" %2s %-25s %-75s %10.2f", count, this.list[i].getName(), this.list[i].getDescription(), this.list[i].getPrice()); } } } return ""; } } import java.util.Scanner; public class MenuOperations { /** * Clear keyboard buffer */ public static void clearBuf(Scanner scanner) { scanner.nextLine(); } /** * Prints the menu */ public static void displayMenu() { System.out.println(" Main menu:"); System.out.println(" A) Add Item " + " G) Get Item " + " R) Remove Item " + " P) Print All Items " + " S) Size " +
  • 13. " D) Update description " + " C) Update price " + " O) Add to order " + " I) Remove from order " + " V) View order " + " Q) Quit "); System.out.println(" Select an operation : "); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Menu menu = new Menu(); //Holds the menu Menu order = new Menu(); //Holds the order int orderCount = 0; //Counts the number of items in the order char choice = ' '; while (true) { displayMenu(); choice = Character.toUpperCase(scanner.next().charAt(0)); clearBuf(scanner); switch (choice) { case 'A': //Add the item to the menu System.out.println(" Enter the name : "); String name = scanner.nextLine(); if(name.length() > 25) { System.out.println("Item name cannot be more than 25."); } else { System.out.println(" Enter the description : "); String desc = scanner.nextLine(); if(desc.length() > 75) { System.out.println("Item description cannot be more than 75."); } else { System.out.println(" Enter the price : "); double price = scanner.nextDouble();
  • 14. clearBuf(scanner); System.out.println(" Enter the position : "); int position = scanner.nextInt(); clearBuf(scanner); MenuItem item = new MenuItem(name, desc, price); try { menu.addItem(item, position); System.out.println("Added "" + name + ": " + desc + """ + " for $" + price + " at position " + position); } catch (FullListException fle) { System.out.println(fle.getMessage()); } } } break; case 'G': //Print out the name, description, and price of the item at the specified position in the menu if(menu.size() > 0) { System.out.println(" Enter position : "); int position = scanner.nextInt(); clearBuf(scanner); MenuItem item = menu.getItem(position); if(item != null) System.out.println(item); else System.out.println("No item found at the specified position"); } else System.out.println("No items in the menu"); break; case 'R': //Remove the item with the given name in the menu if(menu.size() > 0) { System.out.println(" Enter the Name: ");
  • 15. name = scanner.nextLine(); try { menu.removeItem(name); System.out.println("Removed "" + name + """); } catch(IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } else System.out.println("No item"); break; case 'P': //Print the list of all items on the menu menu.printAllItems(); break; case 'S': //Print the number of items on the menu System.out.println("There are " + menu.size() + " items in the menu"); break; case 'D': //Update the description of the named item if(menu.size() > 0) { System.out.println(" Enter the name of the item: "); name = scanner.nextLine(); System.out.println(" Enter the new description: "); String desc = scanner.nextLine(); if(desc.length() > 75) { System.out.println("Item description cannot be more than 75."); } else { try { menu.updateDescription(name, desc); System.out.println("New description set."); } catch(IllegalArgumentException iae) { System.out.println(iae.getMessage()); } }
  • 16. } else System.out.println("No items in the menu"); break; case 'C': //Update the price of the named item if(menu.size() > 0) { System.out.println(" Enter the name of the item: "); name = scanner.nextLine(); System.out.println(" Enter the new price: "); double price = scanner.nextDouble(); try { menu.updatePrice(name, price); System.out.println("Changed the price of "" + name + "" to " + price); } catch(IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch(NonPositivePriceException nppe) { System.out.println(nppe.getMessage()); } } else System.out.println("No items in the menu"); break; case 'O': //Add the item at the specified position in the menu to the order if(menu.size() > 0) { System.out.println("Enter position of item to add to order: "); int position = scanner.nextInt(); clearBuf(scanner); try { MenuItem item = menu.getItem(position); if(item == null) System.out.println("No menu at position : " + position); else { orderCount += 1;
  • 17. order.addItem(item, orderCount); System.out.println("Added "" + item.getName() + "" to order"); } } catch (FullListException fle) { System.out.println(fle.getMessage()); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } else { System.out.println("No menu available to add to order"); } break; case 'I': //Remove the item at the specified position in the order if(order.size() > 0) { System.out.println(" Enter the position : "); int position = scanner.nextInt(); clearBuf(scanner); try { MenuItem item = order.getItem(position); order.removeItem(position); orderCount -= 1; System.out.println("Removed "" + item.getName() + "" from order"); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } else System.out.println("No items in the order"); break; case 'V': //Print item in current order System.out.println("ORDER"); order.printAllItems(); break; case 'Q':
  • 18. // Close scanner scanner.close(); System.exit(0);; break; default: System.out.println("No such operation "); } } } } SAMPLE OUTPUT Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : a Enter the name : Chicken Parmesan Enter the description : Breaded chicken, tomato sauce, and cheese Enter the price : 8.5 Enter the position : 1 Added "Chicken Parmesan: Breaded chicken, tomato sauce, and cheese" for $8.5 at position 1
  • 19. Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : a Enter the name : Hot dog Enter the description : Beef sausage in a bun with ketchup Enter the price : 4.5 Enter the position : 1 Added "Hot dog: Beef sausage in a bun with ketchup" for $4.5 at position 1 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit
  • 20. Select an operation : p # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Hot dog Beef sausage in a bun with ketchup 4.50 2 Chicken Parmesan Breaded chicken, tomato sauce, and cheese 8.50 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : o Enter position of item to add to order: 2 Added "Chicken Parmesan" to order Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order
  • 21. Q) Quit Select an operation : v ORDER # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese 8.50 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : o Enter position of item to add to order: 1 Added "Hot dog" to order Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order
  • 22. V) View order Q) Quit Select an operation : v ORDER # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese 8.50 2 Hot dog Beef sausage in a bun with ketchup 4.50 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : i Enter the position : 1 Removed "Chicken Parmesan" from order Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price
  • 23. O) Add to order I) Remove from order V) View order Q) Quit Select an operation : v ORDER # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Hot dog Beef sausage in a bun with ketchup 4.50 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : q Solution public class FullListException extends Exception { /** * Default constructor */ public FullListException() { super(); } /** * param message
  • 24. */ public FullListException(String message) { super(message); } } public class NonPositivePriceException extends Exception{ /** * Default constructor */ public NonPositivePriceException() { super(); } /** * param message */ public NonPositivePriceException(String message) { super(message); } } public class MenuItem { //Attributes private String name; private String description; private double price; /** * Default constructor */ public MenuItem() { this.name = ""; this.description = ""; this.price = 0.0; } /** * Parameterized Constructor * param name
  • 25. * param description * param price */ public MenuItem(String name, String description, double price) { this.name = name; this.description = description; this.price = price; } /** * return the name */ public String getName() { return name; } /** * param name the name to set */ public void setName(String name) { this.name = name; } /** * return the description */ public String getDescription() { return description; } /** * param description the description to set */ public void setDescription(String description) { this.description = description; } /** * return the price */ public double getPrice() {
  • 26. return price; } /** * param price the price to set * throws NonPositivePriceException */ public void setPrice(double price) throws NonPositivePriceException { if(price <= 0) throw new NonPositivePriceException("Price cannot be set to a non positive value"); this.price = price; } /** * Checks whether this MenuItem has the same attribute values as obj */ Override public boolean equals(Object obj) { MenuItem item = (MenuItem)obj; if((this.name.equalsIgnoreCase(item.name)) && (this.description.equalsIgnoreCase(item.description)) && (this.price == item.price)) return true; else return false; } Override public String toString() { System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description", "Item Price"); System.out.printf(" %50s", new String(new char[115]).replace('0', '-')); System.out.printf(" %2s %-25s %-75s %10.2f", "1", this.name, this.description, this.price); return ""; } } public class Menu{ static final int MAX_ITEMS = 50;
  • 27. //Attributes private MenuItem[] list; /** * Default Constructor * Construct an instance of the Menu class with no MenuItem objects in it * * Postcondition: This Menu has been initialized to an empty list of MenuItems. */ public Menu() { list = new MenuItem[MAX_ITEMS]; } /** * Generates a copy of this Menu. * return The return value is a copy of this Menu. * Subsequent changes to the copy will not affect the original, nor vice versa. * Note that the return value is typecast to an Menu before it can be used. */ Override public Object clone() { Menu clone = new Menu(); if(this.size() > 0) { for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) clone.list[i] = this.list[i]; } } return clone; } /** * Compare this Menu to another object for equality * return A return value of true indicates that obj refers to a Menu object with the same
  • 28. MenuItems in the same order as this Menu. * Otherwise, the return value is false. If obj is null or it is not a Menu object, then the return value is false. */ Override public boolean equals(Object obj) { if((obj == null) || !(obj instanceof Menu)) { return false; } else { Menu menu = (Menu) obj; if(this.size() != menu.size()) return false; else { boolean equal = true; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(!this.list[i].equals(menu.list[i])) { equal = false; break; } } return equal; } } } /** * Returns the number of MenuItems in this Menu * Preconditions: This Menu object has been instantiated. * return : The number of MenuItems in this Menu */ public int size() { int count = 0;
  • 29. for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) count += 1; } return count; } /** * Adds an item at a position * Preconditions: This Menu object has been instantiated and 1 < position < items_currently_in_list + 1. * The number of MenuItem objects in this Menu is less than MAX_ITEMS. * * Postcondition:The new MenuItem is now stored at the desired position in the Menu. * All MenuItems that were originally in positions greater than or equal to position are moved back one position. * (Ex: If there are 5 MenuItems in an Menu, positions 1-5, and you insert a new item at position 4, * the new item will now be at position 4, the item that was at position 4 will be moved to position 5, * and the item that was at position 5 will be moved to position 6). * * param item : the new MenuItem object to add to this Menu * param position : the position in the Menu where item will be inserted * * throws IllegalArgumentException - Indicates that position is not within the valid range. * FullListException - Indicates that there is no more room inside of the Menu to store the new MenuItem object. */ public void addItem(MenuItem item, int position) throws FullListException, IllegalArgumentException{ if(this.list != null) { if(this.size() == MAX_ITEMS) { throw new FullListException("No more room inside of the Menu to store the new MenuItem");
  • 30. } else if((0 < position) && (position < (MAX_ITEMS + 1))) { //Shift menuitems one position forward for(int i = MAX_ITEMS - 1 ; i >= position ; i--) { this.list[i] = this.list[i - 1]; } //Add new item at position this.list[position - 1] = item; } else { throw new IllegalArgumentException("Position not within valid range"); } } } /** * Removes the first menuitem that matches the name * param name - the name of the Menu to be removed * throws IllegalArgumentException */ public void removeItem(String name) throws IllegalArgumentException { if(this.list != null) { boolean found = false; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(!found) { if(this.list[i].getName().equalsIgnoreCase(name)) found = true; } else { //Shift menuitems one position backwards this.list[i - 1] = this.list[i]; } } this.list[MAX_ITEMS - 1] = null; if(!found) throw new IllegalArgumentException("Item does not exist in this Menu"); } }
  • 31. /** * Preconditions: This Menu object has been instantiated and 1 < position < items_currently_in_list. * * Postcondition:The MenuItem at the desired position in the Menu has been removed. * All MenuItems that were originally in positions greater than or equal to position are moved forward one position. * (Ex: If there are 5 items in an Menu, positions 1-5, and you remove the item at position 4, * the item that was at position 5 will be moved to position 4). * * param position - the position in the Menu where the MenuItem will be removed from. * * throws: IllegalArgumentException Indicates that position is not within the valid range. */ public void removeItem(int position) throws IllegalArgumentException { if(this.list != null) { if((0 < position) && (position < (MAX_ITEMS + 1))) { //Shift menuitems one position backwards for(int i = (position - 1) ; i < (MAX_ITEMS - 1) ; i++) { this.list[i] = this.list[i + 1]; } this.list[MAX_ITEMS - 1] = null; } else throw new IllegalArgumentException("Position is not within the valid range"); } } /** * Returns MenuItem at the specified position in this Menu object. * Precondition : This Menu object has been instantiated and 1 < position < items_currently_in_list * param position - position of the MenuItem to retrieve * return * throws: IllegalArgumentException Indicates that position is not within the valid range.
  • 32. */ public MenuItem getItem(int position) throws IllegalArgumentException{ if(this.list != null) { if((0 < position) && (position < (MAX_ITEMS + 1))) { return this.list[position - 1]; } else throw new IllegalArgumentException("Position is not within the valid range"); } return null; } /** * Return the MenuItem with the given name * Preconditions:This Menu object has been instantiated * param name - name of the item to retrieve * return * throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu */ public MenuItem getItemByName(String name) throws IllegalArgumentException{ if(this.list != null) { for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i].getName().equalsIgnoreCase(name)) return this.list[i]; } } throw new IllegalArgumentException("Item does not exist in this Menu"); } /** * Updates the first MenuItem that matches with name with the given description * Preconditions:This Menu object has been instantiated * param name - name of the item * param desc - new description of the menu with Name name * throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu
  • 33. */ public void updateDescription(String name, String newDesc) throws IllegalArgumentException{ if(this.list != null) { boolean found = false; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) { if(this.list[i].getName().equalsIgnoreCase(name)) { found = true; this.list[i].setDescription(newDesc); break; } } } if(!found) throw new IllegalArgumentException("Item does not exist in this Menu"); } } /** * Updates the first MenuItem that matches with name with the given price * Preconditions:This Menu object has been instantiated * param name - name of the item * param price - new price of the menu with Price price * throws - IllegalArgumentException - Indicates that the given item does not exist in this Menu */ public void updatePrice(String name, double newPrice) throws NonPositivePriceException, IllegalArgumentException{ if(this.list != null) { boolean found = false; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) { if(this.list[i].getName().equalsIgnoreCase(name)) {
  • 34. found = true; this.list[i].setPrice(newPrice); break; } } } if(!found) throw new IllegalArgumentException("Item does not exist in this Menu"); } } /** * Prints a neatly formatted table of each item in the Menu on its own line with its position number as shown in the sample output * Preconditions: This Menu object has been instantiated. * Postcondition: A neatly formatted table of each MenuItem in the Menu on its own line with its position number has been displayed to the user. */ public void printAllItems() { this.toString(); } Override public String toString() { if(this.list != null) { int count = 0; for(int i = 0 ; i < MAX_ITEMS ; i++) { if(this.list[i] != null) { if(count == 0) { System.out.printf(" %2s %-25s %-75s %-10s", "#", "Item Name", "Item Description", "Item Price"); System.out.printf(" %50s", new String(new char[115]).replace('0', '-')); } count += 1; System.out.printf(" %2s %-25s %-75s %10.2f", count, this.list[i].getName(),
  • 35. this.list[i].getDescription(), this.list[i].getPrice()); } } } return ""; } } import java.util.Scanner; public class MenuOperations { /** * Clear keyboard buffer */ public static void clearBuf(Scanner scanner) { scanner.nextLine(); } /** * Prints the menu */ public static void displayMenu() { System.out.println(" Main menu:"); System.out.println(" A) Add Item " + " G) Get Item " + " R) Remove Item " + " P) Print All Items " + " S) Size " + " D) Update description " + " C) Update price " + " O) Add to order " + " I) Remove from order " + " V) View order " + " Q) Quit "); System.out.println(" Select an operation : "); } public static void main(String[] args) { Scanner scanner = new Scanner(System.in);
  • 36. Menu menu = new Menu(); //Holds the menu Menu order = new Menu(); //Holds the order int orderCount = 0; //Counts the number of items in the order char choice = ' '; while (true) { displayMenu(); choice = Character.toUpperCase(scanner.next().charAt(0)); clearBuf(scanner); switch (choice) { case 'A': //Add the item to the menu System.out.println(" Enter the name : "); String name = scanner.nextLine(); if(name.length() > 25) { System.out.println("Item name cannot be more than 25."); } else { System.out.println(" Enter the description : "); String desc = scanner.nextLine(); if(desc.length() > 75) { System.out.println("Item description cannot be more than 75."); } else { System.out.println(" Enter the price : "); double price = scanner.nextDouble(); clearBuf(scanner); System.out.println(" Enter the position : "); int position = scanner.nextInt(); clearBuf(scanner); MenuItem item = new MenuItem(name, desc, price); try { menu.addItem(item, position); System.out.println("Added "" + name + ": " + desc + """ +
  • 37. " for $" + price + " at position " + position); } catch (FullListException fle) { System.out.println(fle.getMessage()); } } } break; case 'G': //Print out the name, description, and price of the item at the specified position in the menu if(menu.size() > 0) { System.out.println(" Enter position : "); int position = scanner.nextInt(); clearBuf(scanner); MenuItem item = menu.getItem(position); if(item != null) System.out.println(item); else System.out.println("No item found at the specified position"); } else System.out.println("No items in the menu"); break; case 'R': //Remove the item with the given name in the menu if(menu.size() > 0) { System.out.println(" Enter the Name: "); name = scanner.nextLine(); try { menu.removeItem(name); System.out.println("Removed "" + name + """); } catch(IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } else System.out.println("No item");
  • 38. break; case 'P': //Print the list of all items on the menu menu.printAllItems(); break; case 'S': //Print the number of items on the menu System.out.println("There are " + menu.size() + " items in the menu"); break; case 'D': //Update the description of the named item if(menu.size() > 0) { System.out.println(" Enter the name of the item: "); name = scanner.nextLine(); System.out.println(" Enter the new description: "); String desc = scanner.nextLine(); if(desc.length() > 75) { System.out.println("Item description cannot be more than 75."); } else { try { menu.updateDescription(name, desc); System.out.println("New description set."); } catch(IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } } else System.out.println("No items in the menu"); break; case 'C': //Update the price of the named item if(menu.size() > 0) { System.out.println(" Enter the name of the item: "); name = scanner.nextLine(); System.out.println(" Enter the new price: ");
  • 39. double price = scanner.nextDouble(); try { menu.updatePrice(name, price); System.out.println("Changed the price of "" + name + "" to " + price); } catch(IllegalArgumentException iae) { System.out.println(iae.getMessage()); } catch(NonPositivePriceException nppe) { System.out.println(nppe.getMessage()); } } else System.out.println("No items in the menu"); break; case 'O': //Add the item at the specified position in the menu to the order if(menu.size() > 0) { System.out.println("Enter position of item to add to order: "); int position = scanner.nextInt(); clearBuf(scanner); try { MenuItem item = menu.getItem(position); if(item == null) System.out.println("No menu at position : " + position); else { orderCount += 1; order.addItem(item, orderCount); System.out.println("Added "" + item.getName() + "" to order"); } } catch (FullListException fle) { System.out.println(fle.getMessage()); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } else { System.out.println("No menu available to add to order");
  • 40. } break; case 'I': //Remove the item at the specified position in the order if(order.size() > 0) { System.out.println(" Enter the position : "); int position = scanner.nextInt(); clearBuf(scanner); try { MenuItem item = order.getItem(position); order.removeItem(position); orderCount -= 1; System.out.println("Removed "" + item.getName() + "" from order"); } catch (IllegalArgumentException iae) { System.out.println(iae.getMessage()); } } else System.out.println("No items in the order"); break; case 'V': //Print item in current order System.out.println("ORDER"); order.printAllItems(); break; case 'Q': // Close scanner scanner.close(); System.exit(0);; break; default: System.out.println("No such operation "); } } }
  • 41. } SAMPLE OUTPUT Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : a Enter the name : Chicken Parmesan Enter the description : Breaded chicken, tomato sauce, and cheese Enter the price : 8.5 Enter the position : 1 Added "Chicken Parmesan: Breaded chicken, tomato sauce, and cheese" for $8.5 at position 1 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order
  • 42. V) View order Q) Quit Select an operation : a Enter the name : Hot dog Enter the description : Beef sausage in a bun with ketchup Enter the price : 4.5 Enter the position : 1 Added "Hot dog: Beef sausage in a bun with ketchup" for $4.5 at position 1 Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : p # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Hot dog Beef sausage in a bun with ketchup 4.50 2 Chicken Parmesan Breaded chicken, tomato sauce, and cheese 8.50 Main menu: A) Add Item G) Get Item
  • 43. R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : o Enter position of item to add to order: 2 Added "Chicken Parmesan" to order Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : v ORDER # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese 8.50 Main menu: A) Add Item
  • 44. G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : o Enter position of item to add to order: 1 Added "Hot dog" to order Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : v ORDER # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Chicken Parmesan Breaded chicken, tomato sauce, and cheese 8.50 2 Hot dog Beef sausage in a bun with ketchup 4.50
  • 45. Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : i Enter the position : 1 Removed "Chicken Parmesan" from order Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : v ORDER # Item Name Item Description Item Price ------------------------------------------------------------------------------------------------------------------- 1 Hot dog Beef sausage in a bun with ketchup 4.50
  • 46. Main menu: A) Add Item G) Get Item R) Remove Item P) Print All Items S) Size D) Update description C) Update price O) Add to order I) Remove from order V) View order Q) Quit Select an operation : q