Error and im not sure why? - java

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;

Related

Sum all double values of objects stored in ArrayList (Java)

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

Creating a invoiceline class

Invoice Line class represent some line in the invoice that records the item sold and the quantity.An invoice line should include the following attributes: item Sold: this is an instance variable of type Item.
quantity: an integer that represents the number of units being purchased of this item.Include the following methods in your Invoice Line class: A constructor that takes the following four input parameters: item number, item description, item price, and quantity. The constructor then uses the input parameters to initialize the two instance variables to getters and setters methods for the two instance variable so get Line Total: a method to calculate and return the total price for this line (i.e., quantity * item’s price). to String method that returns a one-line description of the invoice line. The description should include item’s details, quantity purchased, and total cost of the line.
*** I am trying to get the other variables from a different class called item class to the invoiceline class, but I cannot seem to do it. So far I have this. Any Help!?
public class InvoiceLine {
//Instance Variables
private Item itemSold;
private int quantity;
// Constructors
public InvoiceLine(){}
public InvoiceLine(String itemSold, int quantity){
itemSold = new Item(itemSold);
this.quantity = quantity;
}
//Getters
public Item getItemSold(){
return itemSold;
}
public int getQuantity(){
return quantity;
}
//Setters
private void setItemSold(Item itemSold){
this.itemSold = itemSold;
}
private void setQuantity(int quantity){
this.quantity = quantity;
}
// Methods
public double getLineTotal(double total){
total = itemPrice * quantity;
return total;
}
public String toString(){
String invoiceLine = "";
invoiceLine = (itemSold + " brought "+ quantity + ", which the total cost is "+ total);
return invoiceLine;
}
}
Item Class:
public class Item {
//Instance Variables
private int itemNum;
private String itemDescription;
private double itemPrice;
//Constructors
public Item(){}
//Initialize the three variables
public Item(int itemN, String itemDesc, double itemPri){
this.itemNum = itemN;
this.itemDescription = itemDesc;
this.itemPrice = itemPri;
}
public Item(String itemDesc){
this.itemDescription = itemDesc;
this.itemNum = 0;
this.itemPrice = 0;
}
//Getters
public int getItemNum(){
return itemNum;
}
public String getItemDescription(){
return itemDescription;
}
public double getItemPrice(){
return itemPrice;
}
//Setters
private void setItemNum(int itemN){
itemNum = itemN;
}
private void setItemDescription(String itemDesc){
itemDescription = itemDesc;
}
private void setItemPrice(double itemPri){
itemPrice = itemPri;
}
// toString method output description of the item
public String toString(){
String itemDetail = "";
itemDetail = ("Item number is "+ itemNum + ", which is a "+ itemDescription + " and price is " + itemPrice);
return itemDetail;
}
}
Try to change itemSold = new Item(itemSold); to this.itemSold = new Item(itemSold);
In this case the parameter itemSold is shadowing the attribute itemSold, so to access the attribute you have to prefix it with this.

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)

Searching a list of items with a specific name

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

#override to.String printing out only default constructor java hw

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.

Categories