How to Choose more than one item in method in java - java

I have just created a senario that looping which was I have to choose columns what I have selected from data base like this javaMain which have the senario
package myrestorderproject;
import enitities.Menu;
import enitities.Tables;
import java.awt.List;
import java.util.ArrayList;
import java.util.Scanner;
/**
*
* #author DELL
*/
public class MyRestOrderProject {
private static Scanner input;
public static void main(String[] args) {
// TODO code application logic here
input = new Scanner(System.in);
System.out.println("*-*-*-*-*-*Welcome to MyRestaurant*-*-*-*-*-*\n");
System.out.println("Please Choose Table From Tables List");
Tables t = new Tables();
t.getAllRows();
ArrayList<String> listItem = new ArrayList<String>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.print("Enter Table Number: ");
String tableNumber = input.nextLine();
boolean insertedTableNumber = db.goTodataBase.checkTableNumber(tableNumber);
if (insertedTableNumber) {
System.out.println("You Choose Table Number: " + tableNumber);
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
} else {
System.out.println("Table number does not exist");
}
}
}
}
I need now in the part which print "Please Choose Item From Menu List" after I choose the right Item Close the while loop,and I need also to choose more than one item that if I choose Items from menu give me the items was chosen with details getting from menu table
Like If I Choose Item ID 1 +Item ID 2 + Item ID 3 says that you have chosen
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Vegetable Pakora 20.00 veg Starters
Item 1 Chicken Tikka 20.00 Non-veg Starters
after that exit the while loop
as every column have an ID, name, price, type and Category
and this method that am using in previous senario
public static boolean checkMenuItemInDB(String menuId) {
try {
setConnection();
Statement stmt = con.createStatement();
String strCheck = "select * from menu where "
+ "Menu_Id=" + menuId;
stmt.executeQuery(strCheck);
while (stmt.getResultSet().next()) {
return true;
}
} catch (Exception e) {
}
return false;
}
this is menu Class
package enitities;
import javax.swing.JTable;
/**
*
* #author DELL
*/
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public String getAllRows(String itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
}
this is a method which I calls in getAllRows
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}

About the loop :
Programmer tips : You need to avoid as much as possible while(true)-loop.
In your case you could use a system of flag, it will look like :
boolean customerHasFinished = false;
while(!customerHasFinished){
...
//Do your stuff
...
System.out.print("Have you finished ? ");
String hasFinished = input.nextLine();
customerHasFinished = hasFinished.equals("yes");
}
About multiple items :
The best way to store multiple items is to use collection.
In your case, you will probably need to create a Java class that represent an Item. Having fields like name, cost, etc. And then create a collection of Item.
An example with an ArrayList :
List<Item> listItem = new ArrayList<Item>();
boolean orderNotFinished = true;
while (orderNotFinished) {
System.out.println("Please Choose an Item From Menu List");
input = new Scanner(System.in);
String itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(Item.getItemByName(itemChosen)); //Add the chosen item to the list
System.out.print("You want something else ? ");
String hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
}else {
System.out.println("Item Chosen doen't exist");
}
}

Related

How can i verify if i'm adding atributes to a list that are equal?

import entidades.*;
public class Main {
public static void main(String[] args) {
Profissional prof = new Profissional(null, null);
List<Profissional> profissional = new ArrayList<Profissional>();
Scanner sc = new Scanner(System.in);
boolean loop = true;
while(loop == true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.nextLine();
String categoriaPro = sc.nextLine();
prof.NomeVerificacao(profissional, nomePro, categoriaPro);
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissional) {
System.out.println(pro);
This is my Main, it's running fine but i don´t think it is adding the atributes to the list and not verifying either.
i want to add the atributes to a list so i can create different objets but they can not have at least the name equal.
public class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
public void NomeVerificacao(List<Profissional> profissional ,String nome, String categoria) {
if(profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
}else {
for(Profissional pro : profissional) {
if(pro.nome.contentEquals(nome)) {
System.out.println("Já Exite esse nome");
}else {
profissional.add(new Profissional(nome, categoria));
}
}
}
}
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
this is the Profissional Class.
I'm almost there i think but the output keeps saying that the name exists even though it is the first name i'm inserting.
I ran your code on my machine and made 3 changes into it, and it's working for me now,
1)
String nomePro = sc.next();
String categoriaPro = sc.next();
2) In professional class just changed this function a bit:
public void NomeVerificacao(List<Profissional> profissional, String nome, String categoria) {
if (profissional.isEmpty() == true) {
profissional.add(new Profissional(nome, categoria));
} else {
int i = 0;
for (; i < profissional.size(); i++) {
if (profissional.get(i).nome.equals(nome)) {
System.out.println("Já Exite esse nome");
break;
}
}
if (i == profissional.size()) {
profissional.add(new Profissional(nome, categoria));
}
}
}
3) At the end of the class Main, wrote sc.close(); to close the scanner.
i/p and o/p :
1) RP
red
color
2) RP
orange
color
3) RP
orange
paint
Já Exite esse nome
4) SAIR
nome=red, categoria=color
nome=orange, categoria=color
As you can see in above i/p and o/p, nome=red and nome=orange with categoria=color are added in the list but when we tried to add the same nome=orange again but with different category as paint it didn't add it and printed the message "Já Exite esse nome".
and after entering SAIR, the toString(); printed the list content at the end. So the message will be printed only if we try to add the object with the same name again int list (not the first or any other times).
Further optimizations are possible but for now, it will work!
I can propose the following solution:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Set is a data structure that makes sure you don't have a duplicated elements
// in this case we use TreeSet structure that accepts comparator which tells that
// we need to compare elements only by professional's name
Set<Profissional> profissionals = new TreeSet<>(Comparator.comparing(Profissional::getNome));
while (true) {
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
String nomePro = sc.next();
String categoriaPro = sc.next();
// add function returns true in case the element we're going to add
// was not presented in Set structure yet. False otherwise.
boolean isNew = profissionals.add(new Profissional(nomePro, categoriaPro));
if (!isNew) {
System.out.println("Professional with name " + nomePro + " already exists");
} else {
System.out.println("Professional with name " + nomePro + " was added");
}
} else if (comando.contentEquals("SAIR")) {
break;
}
}
// just prints all professionals at the end of the program
profissionals.forEach(System.out::println);
}
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
// getters and setters
#Override
public String toString() {
return "nome=" + nome + ", categoria=" + categoria;
}
}
The output will be the following:
RP
test test
Professional with name test was added
RP
test1 test1
Professional with name test1 was added
RP
test test3
Professional with name test already exists
SAIR
nome=test, categoria=test
nome=test1, categoria=test1
package javaapplication8;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JavaApplication8 {
public static class Profissional {
private String nome;
private String categoria;
public Profissional(String nome, String categoria) {
this.nome = nome;
this.categoria = categoria;
}
}
public static void main(String[] args) {
try {
List<Profissional> profissionalList= new ArrayList<>();
Scanner sc = new Scanner(System.in);
while(true) {
System.out.print("\r\nEnter comando:");
String comando = sc.next().toUpperCase();
if (comando.contentEquals("RP")) {
System.out.print("nome: ");
String nome = sc.next();
sc.nextLine(); // wait enter
System.out.print("categoria: ");
String categoria = sc.next();
sc.nextLine(); // wait enter
// access constructor of Profissional
Constructor profCtor = Profissional.class.getConstructor(String.class, String.class);
profCtor.setAccessible(true);
// create instance of Profissional
Profissional newItem = (Profissional) profCtor.newInstance(nome, categoria);
// avoid duplicate nome in profissionalList
boolean isExist = false;
for(Profissional pro : profissionalList) {
if(pro != null){
if(pro.nome.toLowerCase().equals(newItem.nome.toLowerCase())){
isExist = true;
break;
}
}
}
if(!isExist){
profissionalList.add(newItem );
}
}
if(comando.contentEquals("SAIR")) {
break;
}
}
for(Profissional pro : profissionalList) {
if(pro != null) {
System.out.println("nome: " + pro.nome + " categoria: " + pro.categoria);
}
}
}
catch(Exception ex){
System.out.println(ex.getMessage());
}
}
}

How to read/writetwo HashMap objects to file in Java?

I've been working on a project where I need to write two hash maps to a .dat file in Java. I need to be able to add, remove, and modify an employeeMap hashmap and then write it to a file, and likewise for the other gradeMap HashMap. I don't have any issues adding, removing, or modifying the hashmaps themselves, but I am struggling to write the code to be able to write the objects to a file and read the objects from a file. Here's the class code and main code.
import java.io.Serializable;
//class code
public class Employee implements Comparable<Employee>, Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String fname;
private String lname;
private int ID;
/**
* default constructor for the employee class
*/
Employee()
{
setFname("");
setLname("");
setID(0);
}
/**
*
* #param ln last name
* #param fn first name
* #param id ID number
*/
Employee(String ln, String fn, int id)
{
setFname(fn);
setLname(ln);
setID(id);
}
/**
*
* #return first name of the employee
*/
public String getFname() {
return fname;
}
/**
*
* #param fname first name of the employoee
*/
public void setFname(String fname) {
this.fname = fname;
}
/**
*
* #return last name of the employee
*/
public String getLname() {
return lname;
}
/**
*
* #param lname last name of the employee
*/
public void setLname(String lname){
this.lname = lname;
}
/**
*
* #return ID number
*/
public int getID(){
return ID;
}
/**
*
* #param iD id number
*/
public void setID(int iD)
{
this.ID = iD;
}
public boolean equals(Object obj)
{
if(this == obj)
return true;
else if(obj == null)
return false;
else if(obj instanceof Employee)
{
Employee o = (Employee) obj;
return this.fname.equals(o.fname) && this.lname.equals(o.lname) && this.ID == o.ID;
}
else
return false;
}
public int hashCode()
{
final int HASH_MULTIPLIER = 29;
int h = HASH_MULTIPLIER * fname.hashCode() + lname.hashCode();
h = HASH_MULTIPLIER * h + ((Integer) ID).hashCode();
return h;
}
#Override
public int compareTo(Employee e)
{
if(this.lname.compareTo(e.lname) == 0)
{
if(this.fname.compareTo(e.fname) == 0 )
{
if(this.ID > e.ID)
return 1;
else if(this.ID == e.ID)
return 0;
else
return -1;
}
}
return this.lname.compareTo(e.lname);
}
public String toString()
{
return("Last Name: " + lname + "\nFirst Name: " + fname + "\nID: " + ID);
}
}
Main Code
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.io.ObjectOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Main {
private static Scanner in = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException
{
Map <Integer,Employee> employeeMap;
Map <Employee, Integer> gradeMap;
File f = new File("Employee.dat");
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
if(f.exists())
{
try(ObjectInputStream in = new ObjectInputStream(new FileInputStream(f)))
{
employeeMap = (HashMap<Integer,Employee>) in.readObject();
gradeMap = (HashMap<Employee,Integer>) in.readObject();
}
catch(Exception e)
{
employeeMap = new HashMap<Integer, Employee>();
gradeMap = new HashMap<Employee, Integer>();
}
}
else
{
employeeMap = new HashMap<Integer, Employee>();
gradeMap = new HashMap<Employee, Integer>();
}
int choice = 0;
do
{
choice = printMenuAndGetChoice();
switch(choice)
{
case 1:
addEmployee(employeeMap, gradeMap);
out.writeObject(gradeMap);
out.close();
break;
case 2:
removeEmployee(employeeMap, gradeMap);
out.writeObject(employeeMap);
out.writeObject(gradeMap);
break;
case 3:
modifyEmployee(employeeMap, gradeMap);
out.writeObject(employeeMap);
out.writeObject(gradeMap);
break;
case 4:
display(gradeMap);
break;
case 5:
break;
default:
break;
}
} while(choice != 5);
}
public static int printMenuAndGetChoice()
{
int choice = 0;
System.out.println("1) Add an employee");
System.out.println("2) Remove an employee");
System.out.println("3) Modify information for an employee");
System.out.println("4) Print employees");
System.out.println("5) Exit");
System.out.println("Choice: ");
choice = in.nextInt();
return choice;
}
public static void addEmployee(Map<Integer, Employee> employeeMap, Map<Employee, Integer> gradeMap)
{
Employee newEmployee = new Employee();
System.out.println("Enter the last name for this employee");
newEmployee.setLname(in.next());
System.out.println("Enter the first name for this employee");
newEmployee.setFname(in.next());
System.out.println("Enter the ID for this employee");
newEmployee.setID(in.nextInt());
System.out.println("Enter the work performance value (1 - 5) for this employee");
int performance = in.nextInt();
int x = 0;
Set<Employee> empList = gradeMap.keySet();
for(Employee e: empList)
if(e.equals(newEmployee))
{
System.out.println("Employee already exists!\n");
break;
}
int hash = newEmployee.getID() * newEmployee.hashCode();
employeeMap.put(hash, newEmployee);
gradeMap.put(newEmployee, performance);
}
public static void removeEmployee(Map<Integer, Employee> employeeMap, Map<Employee, Integer> gradeMap)
{
System.out.println("\nEnter the ID number of the employee to be removed: ");
int id = in.nextInt();
if(!employeeMap.containsKey(id))
System.out.println("The employee does not exist.\n Please enter another ID");
else
{
System.out.println("Employee removed:" + employeeMap.get(id).getFname() + " " + employeeMap.get(id).getLname() + "\n");
gradeMap.remove(employeeMap.get(id));
employeeMap.remove(id);
}
}
public static void modifyEmployee(Map<Integer, Employee> employeeMap, Map<Employee, Integer> gradeMap)
{
Set<Employee> empList = gradeMap.keySet();
System.out.println("\nEnter the ID number of the employee to be removed: ");
int id = in.nextInt();
if(employeeMap.containsKey(id) == false)
System.out.println("The employee does not exist.\n Please enter another ID");
else
{
System.out.println("Enter the work performance value (1 - 5) for this employee");
int performance = in.nextInt();
gradeMap.put(employeeMap.get(id), performance);
}
}
public static void display(Map<Employee, Integer> gradeMap)
{
Set<Employee> empList = gradeMap.keySet();
for(Employee e: empList)
System.out.println(e.toString()+ " " + "\nPerformance: " + gradeMap.get(e) + "\n");
}
}
I've been referring to my textbook and online lecture notes and I can't seem to figure out the issue. Anyone have any ideas where I might be doing something wrong(I definitely am)? Thanks for the help.

No Suitable Found for add String

Am trying to retrieve data I Chosen From mysql and filter table the Item I choose by getting value of chosen Item I created A list this list am trying to add on it the chosen Item but I fount an underlined error No Suitable Found for add String
this is my main.java contains code I use
List<Menu> listItem = new ArrayList<Menu>();
if (insertedNumberOfCovers) {
Menu m = new Menu();
m.getAllRows();
while (orderNotFinished) {
System.out.println("Please Choose Item From Menu List");
input = new Scanner(System.in);
itemChosen = input.nextLine();
boolean insertedMenuItemId = db.goTodataBase.checkMenuItemInDB(itemChosen);
if (insertedMenuItemId) {
System.out.println("You Choose Item ID: " + itemChosen);
listItem.add(m.getAllRows(itemChosen));
System.out.print("Do you need to add more Items ? ");
hasFinished = input.nextLine();
orderNotFinished = hasFinished.equals("yes");
} else {
System.out.println("Item Chosen doen't exist");
}
}
and this is Menu.java that I retrieve data from
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package enitities;
import javax.swing.JTable;
public class Menu {
private int Menu_Id;
private String Name;
private float Price;
private String Type;
private String Category;
public int getMenu_Id() {
return Menu_Id;
}
public void setMenu_Id(int Menu_Id) {
this.Menu_Id = Menu_Id;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public float getPrice() {
return Price;
}
public void setPrice(float Price) {
this.Price = Price;
}
public String getType() {
return Type;
}
public void setType(String Type) {
this.Type = Type;
}
public String getCategory() {
return Category;
}
public void setCategory(String Category) {
this.Category = Category;
}
public void getAllRows() {
db.goTodataBase.printData("menu");
}
public Menu getAllRows(Menu itemChosen) {
db.goTodataBase.printData("menu");
return itemChosen;
}
public String getValueByName(String itemChosen) {
String strSelect = "select Menu_Id from menu"
+ "where name=" + Name;
return itemChosen;
}
}
and this method that am Using to Print Table Values
public static void printData(String tableNameOrSelectStatement) {
try {
setConnection();
Statement stmt = con.createStatement();
ResultSet rs;
String strSelectPart = tableNameOrSelectStatement.substring(0, 4).toLowerCase();
String strSelect;
if ("select ".equals(strSelectPart)) {
strSelect = tableNameOrSelectStatement;
} else {
strSelect = "select * from " + tableNameOrSelectStatement;
}
rs = stmt.executeQuery(strSelect);
ResultSetMetaData rsmd = rs.getMetaData();
int c = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= c; i++) {
if (i > 1) {
System.out.print(", ");
}
String columnValue = rs.getString(i);
// System.out.print(columnValue + " " + rsmd.getColumnName(i));
System.out.print(columnValue + " ");
}
System.out.println("");
}
} catch (Exception e) {
Tools.msgBox(e.getMessage());
}
}
the error in this line
listItem.add(m.getAllRows(itemChosen));
The type error is pretty clear to me:
Menu.getAllRows(...) returns String.
listItem.add(...) takes Menu as an argument.
A String is not a Menu. Therefore you have a type error.
That said: you have many, many other things wrong with this code. Names that defy standard Java naming conventions, methods that don't do anything useful (why does getAllRows take Object as an argument but just cast it to a String to return it?), using float to store a currency value, and probably more.

Calculate the number of items within the a Shopping Cart

I am quite new to the concepts of Java. I have designed a shopping cart application using core java. But i am not able to get the desired output.
Here is my pojo class item.java
package com.shop.data.*;
public class Item
{
private int Itemid;
private String category;
private String name;
private double price;
private String size;
/**
* #return the category
*/
public String getCategory() {
return category;
}
public Item(int itemid) {
super();
Itemid = itemid;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemcategory ,String itemName, double itemPrice,String itemSize)
{
name = itemName;
price = itemPrice;
size = itemSize;
category = itemcategory;
}
public Item(String itemName, int itemPrice, String size) {
// TODO Auto-generated constructor stub
}
/**
* #return the size
*/
public String getSize() {
return size;
}
/**
* #param size the size to set
*/
public void setSize(String size) {
this.size = size;
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
/**
* #return the itemid
*/
public int getItemid() {
return Itemid;
}
/**
* #param itemid the itemid to set
*/
public void setItemid(int itemid) {
Itemid = itemid;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
public String toString ()
{
return (name + "\t" + price + "\t"+ size + "\t");
}
}
The main class is ShopCartTest.java
package com.shop.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.shop.data.*;
public class ShoppingCartTest {
private static Scanner scan;
public static void main(String[] args) {
// *** declare and instantiate a variable cart to be an empty ArrayList
shopping();
}
public static void shopping() {
ArrayList<Item> ItemCart = new ArrayList<Item>();
Map<Item, Integer> Quantity = new HashMap<Item, Integer>();
Item item = null;
Inventory inventory = null;
String category = null;
String itemName;
String itemSize;
double itemPrice = 0;
double totalPrice = 0.0;
double sum = 0.0;
int itemquantity;
scan = new Scanner(System.in);
String keepShopping = "y";
System.out.println("****Shopping Cart****");
do {
System.out.println("Select Category: ");
category = scan.nextLine();
if (category.equals("men") || category.equals("Men")) {
System.out
.println("Available Items: \n1Shirt : 900 \n2.T-Shirt : 700 \n3.Jean: 1500.\n");
System.out.println("Select Item to Add to your Bag: ");
itemName = scan.nextLine();
if (itemName.equals("Shirt") || (itemName.equals("shirt"))) {
itemPrice = 900;
} else if (itemName.equals("T-Shirt")
|| (itemName.equals("t-shirt"))) {
itemPrice = 700;
} else
itemPrice = 1500;
} else {
System.out
.println("Available Items: \n1.Dress : 250 \n2.Top : 350 \n3.Jean: 1500.\n");
System.out.println("Select Item to Add to your Bag: ");
itemName = scan.nextLine();
// *** create a new item and add it to the cart
if (itemName.equals("Dress") || (itemName.equals("dress"))) {
itemPrice = 250;
} else if (itemName.equals("Top") || (itemName.equals("top"))) {
itemPrice = 350;
} else
itemPrice = 1500;
}
System.out.print("Available Sizes \nS \tM \tL: ");
itemSize = scan.nextLine();
System.out.print("Enter the quantity: ");
itemquantity = scan.nextInt();
item = new Item(category, itemName, itemPrice, itemSize);
ItemCart.add(item);
Quantity.put(item, itemquantity);
// *** print the contents of the cart object using println
for (int i = 0; i < ItemCart.size(); i++) {
Item itm = ItemCart.get(i);
System.out.println(itm);
}
// Print out the results
System.out.print("Continue shopping (y/n)? ");
scan.nextLine();
keepShopping = scan.nextLine();
} while (keepShopping.equals("y"));
for (int i = 0; i < ItemCart.size(); i++) {
Quantity.put(item, itemquantity);
Item itm = ItemCart.get(i);
System.out.println(itm);
totalPrice = itemquantity * itm.getPrice();
for (int j = 0; i < ItemCart.size(); i++)
sum += totalPrice;
}
System.out.println("The total price is: " + sum);
System.out.println("Do you wan to proceed to checkout (y/n): ");
if (scan.nextLine().equals("y")) {
System.out.println("Thank you for shopping with us!");
} else {
shopping();
}
}
}
There are 4 pojo's Cart, inventory,Item, User. The user must be able to select multiple items of multiple quanties. (For items a list is been created and for the quantity: map. where item object is the key and quantity is the value). The user slects category, item, then quatity. Then he can proceed to checkout. So when he decides to checkout. He must be able to see the various items purchased ie (itemName, SIxe ,UnitPrice, unitprice*quantity) and finally the Total Price.
How do i achieve this? I am kinda lost!
Some pointers:
You should use proper naming conventions (i.e. variables and methods name starts with a lower case letter)
ItemCart is redundant, you can remove it and use the keys of Quantity
a Map provides an entrySet method, using that on Quantity will help you list the items in the cart (keys) and compute the total price using the item (key) price and quantity (value)

How to remove an element previously added into an array?

Could you please help me figure out how will I make it possible to create a delete command?
in selection 5. I must use array not ArrayList neither Vector?
//Package ask1 main class Library
package ask1;
import java.lang.Object.*;
import java.util.Scanner;
import java.util.Arrays;
import java.io.*;
public class library {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
Management manager = new Management();
Scanner input = new Scanner( System.in );
Book vivlio = new Book();
System.out.println("\n\t\t^*^*^*^*^*^*^* LIBRARY MANAGEMENT ^*^*^*^*^*^*^");
while(true){
System.out.println("------------------MENU-------------------------------");
System.out.print("\nENTER UR CHOICE\n\t1:Add a new Book\n\t2:Edit Book Infos\n\t3:Search a Book (with ISBN)\n\t4:Show all the Books\n\t5:Delete a Book (with ISBN)\n\t6:Exit \n :");
int selection;
selection=input.nextInt();
if (selection == 1)
{
System.out.println("Adding a new book ");
String empty = input.nextLine();
System.out.println("name of book:");
vivlio.name = input.nextLine();
System.out.println("Author:");
vivlio.author = input.nextLine();
System.out.println("ISBN:");
vivlio.isbn = input.nextLine();
System.out.println("Number of copies:");
vivlio.number = input.nextInt();
System.out.println("");
manager.AddBook(vivlio);
}
else
if (selection == 2) {
System.out.println("Editing a Book ");
System.out.println("Please enter title of book to edit:");
String title = input.next();
Book editingBook = findBookByTitle(title);
if(editingBook == null) {
System.out.println("Sorry no book found with title name = " + title);
} else {
//ask user for new price etc what ever you want to edit.
System.out.println("Please enter new values:");
String newValue = input.nextLine();
editingBook.setPrice(newValue);
// etc. other editing to book.
}
}
else
if (selection == 3)
{
System.out.println("Searching a Book ");
}
else
if (selection == 4)
{
System.out.println("You Choose to view all the Books ");
manager.PrintAllBooks();
}
else
if (selection == 5)
{
System.out.println("You Choose to Delete a Book ");
String empty = input.nextLine();
}
else
if(selection == 6)
{
System.out.println("Library System Terminated!!! ");
String empty = input.nextLine();
System.exit(0);
}
else
{
System.out.println("Wrong Choice");
}
}
}
private static Book findBookByTitle(String title) {
// TODO Auto-generated method stub
return null;
}
here is the second class called Book
package ask1;
import java.util.Scanner;
public class Book {
Scanner input = new Scanner( System.in );
public String isbn;
public String name;
public String author;
public int number;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
String bookinfo = name + " ," + author + " ," + isbn;
public void setPrice(String newPrice) {
// TODO Auto-generated method stub
}
}
And the third class called Management
package ask1;
import java.lang.reflect.Array;
import java.util.Scanner;
import java.util.Arrays;
public class Management {
public Book[] books =new Book [60];
String Sisbn;
int current = 0;
Library lib = new Library ();
Scanner input = new Scanner( System.in );
//Number 1
public void AddBook(Book vivlio)
{
books[current]=vivlio;
current++;
}
//Number 2
public Book findBookByTitle(String title)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getName().equalsIgnoreCase(title))
{
searchBook = vivlio;
System.out.println("New name of book:");
vivlio.setName(input.nextLine());
System.out.println("New Author of book:");
vivlio.setAuthor(input.nextLine());
System.out.println("New isbn of book:");
vivlio.setIsbn(input.nextLine());
System.out.println("New number of copies of book:");
vivlio.setNumber(input.nextInt());
break; }
}
return searchBook;
}
public String getSisbn() {
return Sisbn;
}
public void setSisbn(String sisbn) {
Sisbn = sisbn;
}
public Book[] getBooks() {
return books;
}
public void setBooks(Book[] books) {
this.books = books;
}
public int getCurrent() {
return current;
}
public void setCurrent(int current) {
this.current = current;
}
//Number3
public Book findBookByISBN(String isbn)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getIsbn().equalsIgnoreCase(isbn))
{
searchBook = vivlio;
String book = vivlio.getName();
lib.once=vivlio.getName();
System.out.println(lib.once);
break;
}
}
return searchBook;
}
//Number 4
public void PrintAllBooks()
{
for (int i=0;i<current;i++)
{
Book b = books[i];
System.out.println(b.name);
}
}
//number 5
public Book DeleteWithIsbn(String isbn)
{
Book searchBook = null;
for (Book vivlio : books)
{
if(vivlio.getIsbn().equalsIgnoreCase(isbn))
{
searchBook = vivlio;
books[current]=null;
for (int i=0;i<current;current--)
{
Book b = books[i];
System.out.println(b.name);
break;
}
}
}
return searchBook;
}
}
Your code doesn't attempt to 'delete' it still finds. Try the following instead:
(Untested but gives you the idea)
public boolean DeleteWithIsbn(String isbn) {
int index = 0;
for (Book vivlio : books) {
if(vivlio.getIsbn().equalsIgnoreCase(isbn)) { //find the right book
for (int i = index; i < books.length - 1; i++) {
books[i] = books[i+1]; //move all the other books up
}
books[books.length -1] = null; //reset the last one in the array
return true;
}
count++;
}
return false;
}
This method will return false if it cannot find the book. It returns true otherwise.
Of course this all assumes that the book only ever exists once in the array.
First, fix your indentation on your if/else statements, and consider using a case statement instead.
Second, your Selection 5 isn't actually deleting anything -- it's just setting String empty to the next line. Get the user-inputted ISBN with Scanner, and make sure to call Book.DeleteBookWithISBN(isbn) with that isbn. Then it'll do what you want :)

Categories