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)
Related
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");
}
}
I have an ArrayList that contains objects. Each of the object has 3 values: String name, double price, int quantity. How to write method that will sum all doubles of objects and print the result. And also if int quantity>1, price will be multiplied by quantity.
Code that i wrote so far:
Product class
public class Product {
private String name;
private double price;
private int quantity;
public Product(String name, double price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public static Product createProduct(String name, double price, int quantity){
return new Product(name, price, quantity);
}
}
Product list class
import java.util.ArrayList;
import java.util.List;
public class ProductList {
private String name;
List<Product> newList;
public ProductList(String name) {
this.name = name;
this.newList = new ArrayList<>();
}
public boolean addNewProduct(Product product) {
if (findProduct(product.getName()) >= 0) {
System.out.println("Product is already on the list");
return false;
}
newList.add(product);
return true;
}
public boolean removeProduct(Product product) {
if (findProduct(product.getName().toUpperCase()) < 0) {
System.out.println("Product not found");
return false;
}
newList.remove(product);
return true;
}
private int findProduct(String productName) {
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
if (product.getName().equals(productName)) {
return i;
}
}
return -1;
}
public Product queryProduct(String name) {
int position = findProduct(name);
if (position >= 0) {
return this.newList.get(position);
}
return null;
}
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
sum += newList.get(i).getPrice();
}
return sum;
}
/*public boolean listProducts(){};
public boolean updateProduct(){};
*/
}
Simulation class:
public class Simulation {
private static Scanner scanner = new Scanner(System.in);
private static ProductList myProductList = new ProductList("My list");
private static void addNewProduct() {
System.out.println("Enter new product name: ");
String name = scanner.nextLine();
System.out.println("Enter new product price: ");
double price = scanner.nextDouble();
System.out.println("Enter new product quantity");
int quantity = scanner.nextInt();
Product newProduct = Product.createProduct(name, price, quantity);
if (myProductList.addNewProduct(newProduct) == true) {
System.out.println("New product added: " + name + " | price: " + price + " | quantity: " + quantity);
}
}
private static void removeProduct() {
System.out.println("Enter product name: ");
String name = scanner.nextLine().toUpperCase();
Product existingProduct = myProductList.queryProduct(name);
if (existingProduct == null) {
System.out.println("No such product");
return;
}
if (myProductList.removeProduct(existingProduct)) {
System.out.println("Sucessfully deleted product: " + existingProduct.getName());
} else {
System.out.println("Error deleting");
}
}
private static void printActions() {
System.out.println("Avaiable actions");
System.out.println("press: ");
System.out.println("0 - to shut down\n" +
"1 - to add new product\n" +
"2 - to remove product\n" +
"3 - to sum all products");
}
private static void sumProducts(){
myProductList.sumProducts();
}
public static void main(String[] args) {
printActions();
boolean quit = false;
while (!quit)
try {
System.out.println("\nEnter action: ");
int action = scanner.nextInt();
scanner.nextLine();
switch ((action)) {
case 0:
System.out.println("\nShutting down...");
quit = true;
break;
case 1:
addNewProduct();
break;
case 2:
removeProduct();
break;
}
} catch (InputMismatchException e) {
System.out.println("Bad key pressed, only values form 0 to 2 accepted");
scanner.nextLine();
}
}
}
Thanks in advance
You can do it in one line using Java 8.
public double sumProducts() {
return newList.stream().mapToDouble(product -> product.getPrice() * product.getQuantity()).sum();
}
If you use double to store the price, you will get incorrect answers when you try to add and multiply the values. For example, 0.1 + 0.2 is NOT the same double as 0.3. If you want accurate arithmetic for decimal numbers, you should use the BigDecimal class in place of double. If you don't do that, I can guarantee that your program will sometimes give wrong answers.
So you need to change your Product class as follows.
public class Product {
private String name;
private BigDecimal price;
private int quantity;
public Product(String name, BigDecimal price, int quantity) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public BigDecimal getPrice() {
return price;
}
public static Product createProduct(String name, BigDecimal price, int quantity){
return new Product(name, price, quantity);
}
}
You will also need to make corresponding changes in the code that calls the methods of this class.
Once you've done that, you can use the methods of the BigDecimal class to do arithmetic. It might look something like this.
public BigDecimal calculateTotalPrice() {
BigDecimal total = BigDecimal.ZERO;
for (Product product : newList) {
BigDecimal linePrice = product.getPrice().multiply(new BigDecimal(product.getQuantity()));
total = total.add(linePrice);
}
return total;
}
the sum of each product was missing multiply by its quantity.
public double sumProducts() {
double sum = 0;
for (int i = 0; i < newList.size(); i++) {
Product product = newList.get(i);
sum += product.getPrice() * product.getQuantity();
}
return sum;
}
I am doing an Object Oriented program which contains a class Catalog and a class Products. Catalog has a method which suppose to search a list of products with a specific name that are read from a file. Everything works but the getProducts is not working.
This is the Catalog class with the getProducts(String name)
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*
public class Catalog{
private static int MAX_ITEMS = 10;
private Products[] list;
private int nextItem;
/**
* Default constructor
*/
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
/**
* Reads items from an input file.
*/
public void loadList(String fileName)
throws FileNotFoundException {
if ( (fileName != null) && (!fileName.equals("")) ) {
Scanner input = new Scanner(new File(fileName));
String newLine = null;
String name = null;
int quantity = 0;
double price = 0.0;
while (input.hasNextLine() && nextItem < MAX_ITEMS) {
if (input.hasNext()) {
name = input.next();
} else {
System.err.println("ERROR Not a String");
System.exit(2);
}
if (input.hasNextInt()) {
quantity = input.nextInt();
} else {
System.err.println("ERROR Not an integer");
System.exit(2);
}
if (input.hasNextDouble()) {
price = input.nextDouble();
} else {
System.err.println("ERROR Not a double");
System.exit(2);
}
list[nextItem] = new Products(name, quantity, price);
newLine = input.nextLine();
nextItem += 1;
}
}
return;
}
/**
* Calculate the total cost of products.
*/
public double getTotalPrice(){
double total = 0.0;
for(int i=0; i < nextItem; i++){
Products products = list[i];
total+=products.getTotalPrice();
}
return total;
}
/**
* Search Catalog items with a product name and returns it to caller
*/
public Products getProducts(String name){
**//search a list for string equality using the name of the product and returns it to the caller**
for(int i=0; i<nextItem; i++){
Products item = list[i];
if(item.equals(name)){
return item; //What is suppose to be returned or how to
//return it to the caller
}
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}
This is Products class
public class Products {
private String name;
private int quantity;
private double price;
/**
* Constructor.
*/
public Products(String name, int quantity, double price){
this.name = name;
this.quantity = quantity;
this.price = price;
}
/**
* Gets name of the product.
*/
public String getName(){
return this.name;
}
/**
* Gets the quantity of products.
*/
public int getQuantity(){
return this.quantity;
}
/**
* Gets the cost per product.
*/
public double getPrice(){
return price;
}
/**
* set quantity of the products.
*/
public void setQuantity(int quantity){
this.quantity=quantity;
}
/**
* Calculate the total price.
*/
public double getTotalPrice(){
return quantity * price;
}
/**
* Returns a spaced-separated list of the attributes.
*/
public String toString(){
toStr="";
toStr= toStr + getName();
return toStr;
}
This is the file
Football 2 15.50
Football-Jersey 2 30.95
ChapStick 1 3.87
Book 4 10.00
Book-Journal 1 5.00
You have:
public Products getProducts(String name){
...
for(int i=0; i<nextItem; i++){
...
Products item = list[i];
if(item.equals(name)) {
...
Notice that item is a Products but you are comparing it to the String, name. You would want to compare the product's name, e.g.:
if(item.getName().equals(name)) {
You can also use String.equalsIgnoreCase() if names are case-insensitive, possibly using trim() first if leading/trailing whitespace is an issue, too.
Item is an Object, so you can try to get the name by using dot like this
if(item.getName().equals(name))
or
if(item.getName.equalsIgnoreCase(name))
At the end of my for loop, Id like to print out all the objects in the array. I used a generate toString with string builder from Source, however, after the loop is done executing, it prints out the default values of variables Item:
[Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], Item [getPrice()=0.0, getName()=No Name yet., getPriority()=-1.0], null]
heres my code
public class Item {
static Item list[]=new Item [7];
public static int x = 0;
public static String setName;
public static double setPrice;
public static int setPrioirty;
private int priority=-1;
private double price;
private String name;
Item(){
priority=-1;
price=0;
name="No Name yet.";
}// default constructor.
public Item(int i, double j, String k) {
setItem(i,j,k); //constructor with 3 arguments.
}
public void setItem (int i, double j, String k){ // setting item with 3 attributes.
setPriority(i);
setPrice(j);
setName(k);
}
public void setName(String k) { //setting individual attributes in item.
// TODO Auto-generated method stub //page 378
name=k;
}
public void setPrice(double j) {//setting individual attributes in item.
// TODO Auto-generated method stub
if (j<0||j>100){
System.out.println("Error: price is too low or high");
}
else
price=j;
}
public void setPriority(int i) {//setting individual attributes in item.
// TODO Auto-generated method stub
priority =((i>=0&&i<7)?i:0);
}
public double getPrice(){
return price;
}
public String getName(){
return name;
}
public double getPriority(){
return priority;
}
public static void add(Item itemObject) {
if (x<7)
{
list[x]=itemObject;
System.out.println("Item added at index " + x);
x++;
}
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [getPrice()=").append(getPrice()).append(", ");
if (getName() != null)
builder.append("getName()=").append(getName()).append(", ");
builder.append("getPriority()=").append(getPriority()).append("]");
return builder.toString();
}
}
main
import java.util.Arrays;
import java.util.Scanner;
import java.util.Set;
public class homework3main extends Item {
#SuppressWarnings("static-access")
public static void main(String[] args) {
//item list[]=new item [7]; // array of objects
Scanner keyboard= new Scanner(System.in);
for(int x=1; x<7;x++){
Item itemObject=new Item ();
//Item itemObject=new Item (setPrioirty,setPrice,setName);
//creating new object with 3 variables, name, price, priority
//list[x]=new Item();// is this right?
System.out.println("Enter an item you want to add to your list "+ x);
list[x].setName=keyboard.next();
System.out.println("Enter a price "+x);
list[x].setPrice=keyboard.nextDouble();
System.out.println("Enter the priority of the item "+x);
list[x].setPrioirty=keyboard.nextInt();
//item itemObject=new item (setPrioirty,setPrice,setName);
list[x].add(itemObject);
}
System.out.println(Arrays.toString(list));
My conditional statements dont work either in my Set methods. Cant understand why those dont work, they are pretty straight forward.
you appear to have several structural issues with the code so here is what i think it should be:
import java.util.Arrays;
import java.util.Scanner;
public class Item {
//the properties of an Item
private int priority;
private String name;
private double price;
//default constructer
public Item() {
priority = -1; //fill with default values
price = 0.0;
name = "No name yet";
}
//constructer with all fields given
public Item(int priority, String name, double price) {
this.priority = priority; //there are two instances of each variable
this.name = name; // use 'this.' to distinguish them
this.price = price;
}
// all getters simply will return the corresponding field
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 0 and 7
if (priority >= 0 && priority <= 7) {
this.priority = priority;
} else {
//otherwise default to 0
this.priority = 0;
}
}
public String getName() {
return name;
}
public void setName(String name) {
//no constraints on the name so simply assign it
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0) {
if (price <= 100) {
this.price = price;
} else {
//use System.err for errors
// used nested ifs so you can tell if price is to high or low
//otherwise it is a bit ambiguous
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
//your tostring is fine
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [getPrice()=").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("getName()=").append(getName()).append(", ");
}
builder.append("getPriority()=").append(getPriority()).append("]");
return builder.toString();
}
//just put your main here
//if you can't then put it in a class but don't sub-class this class
public static void main(String[] args) {
//put your list declaration here
//it doesn't quitemake sense for the Item calss to have a field
//called list in this instance
Item[] list = new Item[7];
Scanner keyboard = new Scanner(System.in);
//i is the most commonly used variable for 'for' loops
for (int i = 1; i <= list.length; i++) {
//create a new item
Item anItem = new Item();
//call your methods on that object to set its fields
System.out.println("Enter an item you want to add to your list " + i);
anItem.setName(keyboard.next());
System.out.println("Enter a price " + i);
anItem.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item " + i);
anItem.setPriority(keyboard.nextInt());
//use the var i for the position
//remember to subtract 1 since arrays start at 0 but i starts at 1
list[i-1] = anItem;
}
System.out.println(Arrays.toString(list));
}
}
In your condition
j < 0 && j > 100
How can j both be smaller than 0 and greater than 100? You need ||.
In your methods
System.out.println("Enter an item you want to add to your list "+ x);
list[x].setName=keyboard.next();
System.out.println("Enter a price "+x);
list[x].setPrice=keyboard.nextDouble();
System.out.println("Enter the priority of the item "+x);
list[x].setPrioirty=keyboard.nextInt();
you are setting the static fields of the Item class, not the fields of the instance. Either use the setters you have or use the constructor. For example
Item itemObject = new Item ();
System.out.println("Enter an item you want to add to your list "+ x);
itemObject.setName(keyboard.next());
System.out.println("Enter a price "+x);
itemObject.setPrice(keyboard.nextDouble());
System.out.println("Enter the priority of the item "+x);
itemObject.setPriority(keyboard.nextInt());
list[x] = itemObject;
You're completely overusing setters by the way. Go through this tutorial.
This is my main method. For some reason, it is not finding my shoppingcart class and is throwing me an error.
package goshopping;
import java.util.Scanner;
public class Shopping
{
static final Scanner scanner = new Scanner(System.in);
public static void main (String[] args)
{
ShoppingCart cart=new ShoppingCart();
String name;
double price;
int quantity;
String shopMore;
do
{
System.out.print("Please enter the name of item: ");
name=scanner.nextLine();
System.out.print("Please enter the price of the item: ");
price=scanner.nextDouble();
scanner.nextLine();
System.out.print("Please enter the quantity of the item: ");
quantity=scanner.nextInt();
scanner.nextLine();
cart.addToCart(name, price, quantity);
System.out.println(cart.toString());
System.out.print("Shop some more? Enter Y for yes or N for no ");
shopMore=scanner.nextLine();
}
while(shopMore.charAt(0)=='Y'||shopMore.charAt(0)=='y');
}
}
This is my second class ShoppingCart.java which is saying it cant find variables but I have instantiated them already....
package shoppingcart;
// **********************************************************************
// ShoppingCart.java
//
// Represents a shopping cart as an array of items
// **********************************************************************
import java.text.NumberFormat;
public class ShoppingCart
{
private int itemCount; // total number of items in the cart
private double totalPrice; // total price of items in the cart
private int capacity; // current cart capacity
private Item[] cart;
// -----------------------------------------------------------
// Creates an empty shopping cart with a capacity of 5 items.
// -----------------------------------------------------------
public ShoppingCart()
{
capacity = 5;
itemCount = 0;
totalPrice = 0.0;
cart=new Item[capacity];
}
// -------------------------------------------------------
// Adds an item to the shopping cart.
// -------------------------------------------------------
public void addToCart(String itemName, double price, int quantity)
{
cart[itemCount]=new Item(itemName,price,quantity);
totalPrice+=price;
itemCount++;
if(itemCount==capacity)
{
increaseSize();
}
}
// -------------------------------------------------------
// Returns the contents of the cart together with
// summary information.
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String contents = "\nShopping Cart\n";
contents += "\nItem\t\tUnit Price\tQuantity\tTotal\n";
for (int i = 0; i < itemCount; i++)
contents += cart[i].toString() + "\n";
contents += "\nTotal Price: " + fmt.format(totalPrice);
contents += "\n";
return contents;
}
// ---------------------------------------------------------
// Increases the capacity of the shopping cart by 3
// ---------------------------------------------------------
private void increaseSize()
{
Item[] temp=new Item[capacity+3];
System.arraycopy(cart, 0, temp, 0, capacity);
cart=temp;
}
}
This is my third class called Item.java This class is fine no errors here
package item;
// ***************************************************************
// Item.java
//
// Represents an item in a shopping cart.
// ***************************************************************
import java.text.NumberFormat;
public class Item
{
private String name;
private double price;
private int quantity;
// -------------------------------------------------------
// Create a new item with the given attributes.
// -------------------------------------------------------
public Item (String itemName, double itemPrice, int numPurchased)
{
name = itemName;
price = itemPrice;
quantity = numPurchased;
}
// -------------------------------------------------------
// Return a string with the information about the item
// -------------------------------------------------------
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
return (name + " \t" + fmt.format(price) + " \t" + quantity + " \t"
+ fmt.format(price*quantity));
}
// -------------------------------------------------
// Returns the unit price of the item
// -------------------------------------------------
public double getPrice()
{
return price;
}
// -------------------------------------------------
// Returns the name of the item
// -------------------------------------------------
public String getName()
{
return name;
}
// -------------------------------------------------
// Returns the quantity of the item
// -------------------------------------------------
public int getQuantity()
{
return quantity;
}
}
Import the class ShoppingCart in the Shopping class file.
import shoppingcart.ShoppingCart;
If you are using Eclipse, just Ctrl + Shift + O
You will need to import the shoppingcart package
import shoppingcart.ShoppingCart;
U'll have to import ShoppingCart in your Shopping class.
Below
package goshopping;
in your Shopping class add this.
import shoppingcart.ShoppingCart;