I have two equals methods in code, yet neither of them work. I made one myself and then I also auto generated one from Eclipse via source. I've run the program multiple times with one or an other and again, neither work.
import java.util.Arrays;
import java.util.Scanner;
import java.math.*;
public class Item {
static //the properties of an Item
double cash=59;
static double sum=0;
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";
}
public Item(int priority, String name, double price) {//constructor with all 3 arguments
this.priority = priority;
this.name = name;
this.price = price;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
//priority must be between 1 and 7
if (priority > 0 && priority <= 7) {
this.priority = priority;
} else {
//otherwise default to 0
System.err.println("Error, enter 1 through 7");
//this.priority = 0;
}
}
public String getName() {
return name;
}
public void setName(String name) {
//would I put equals method here. name.equals.name?
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
//price between 0 and 100 inclusive
if (price >= 0.00) {
if (price <= 100.00) {
this.price = price;
cash = cash-=price;
sum=sum+=price;
} else {
System.err.println("Error: price to high");
}
} else {
System.err.println("Error: price to low");
}
}
public boolean equals(Item otherItem){
if(this.getPriority()==otherItem.getPriority());
System.err.println("Error, Same Priorities detected");
return true;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + priority;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Item)) {
return false;
}
Item other = (Item) obj;
if (priority != other.priority) {
return false;
}
System.err.println("Error, Same Priorities detected");
return true;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Item [Price=").append(getPrice()).append(", ");
if (getName() != null) {
builder.append("Name=").append(getName()).append(", ");
}
builder.append("Priority=").append(getPriority()).append("]");
return builder.toString();
}
public static void main(String[] args) {
Item[] list = new Item[2];
Scanner keyboard = new Scanner(System.in);
for (int i = 1; i <= list.length; i++) {
if(cash==59)
{
System.out.println("You have 59 dollars");
}
Item anItem = new Item(); // new item object created 7 times
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());
list[i-1] = anItem;
System.out.println(Arrays.toString(list));
System.out.println("Cash left "+cash);
System.out.println("Sum of Items "+sum);
if(sum>59)
{System.out.println("Error, you ran out of money");
System.out.println(Arrays.toString(list));}
}
System.out.println( list[1].getPriority());
}
}
This method here is completely biting you in the a**
public boolean equals(Item otherItem){
if(this.getPriority()==otherItem.getPriority());
System.err.println("Error, Same Priorities detected");
return true;
}
First, there's an ; after the if's condition so it's not doing anything and therefore your method is always returning true.
Second, this method overloads the equals(Object) method that you should be overriding and using. Get rid of it.
When overriding methods, annotate them with #Override. With an IDE that will do a check and validate that you are actually trying to override a method.
Related
I have an assignment where i am to create a program that manages CDs. I am using switch statement and in the first switch case I have to add a CD to the array but only if a CD with the same ID doesn't already exist in the array.
I've tried with
if (CDid != null && !CDid.equals(CDid.getCdId) {
cdArray[counter] = cd_obj;
counter++;
} else {
counter = cdArray.length-1;
System.out.println("The array is full");
}
I've also tried a for each loop before the if statement but nothing works. Either i get the nullpointer exception and/or the cd wont add to the array.
I am not allowed to have any nullpointerexceptions in the code and I am stuck on this problem for 2 days now so im hoping someone out there can help me!
Sorry for any errors ive made this is my first time posting a question on Stacksoverflow
The following code is the CD Main class
public class Cd_main {
public static void main(String[] args){
boolean running = true;
String CDid, CDgenre, CDartist, CDalbum, CDstorageSpot, CDtrackAmount,
CDstorageAmount CDprice, searchGenre, deleteCD ;
CD[] cdArray = new CD[25];
int counter = 0;
int choice;
Scanner scanner = new Scanner(System.in);
while(running){
............................
............................
choice = scanner.nextInt();
switch(choice){
case 1:
System.out.println("......");
System.out.println("............");
CDid = scanner.next();
CDgenre = scanner.next();
CDartist = scanner.next();
CDalbum = scanner.next();
CDstorageSpot= scanner.next();
CDtrackAmount= scanner.next();
CDstorageAmount = scanner.next();
CDprice = scanner.next();
CD cd_obj = new CD(CDid, CDgenre, CDartist, CDalbum,
CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);
if(CDid.equalsIgnoreCase(CDid.getCdId())){
cdArray[counter] = cd_obj;
counter++;
}else{
counter = cdArray.length-1;
System.out.println("The array is full");
}
}
break;
```
The CD class:
```
public class CD {
public String cd_ID;
public String genre;
public String artist;
public String album;
public String storageSpot;
public String trackAmount;
public String storageAmount;
public String price;
public CD() {
}
public CD(String cd_ID, String genre, String artist, String album,
String storageSpot, String trackAmount, String storageAmount,
String price){
this.cd_ID = cd_ID;
this.genre = genre;
this.artist = artist;
this.album = album;
this.storageSpot = storageSpot;
this.trackAmount = trackAmount;
this.storageAmount = storageAmount;
this.price = price;
}
public String getCdId() {
return this.cd_ID;
}
public void setCdId(String cd_ID) {
this.cd_ID = cd_ID;
}
public String getGenre() {
return this.genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getArtist() {
return this.artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return this.album;
}
public void setAlbum(String album) {
this.album = album;
}
public String getStorageSpot() {
return this.storageSpot;
}
public void setStorageSpot(String storageSpot) {
this.storageSpot = storageSpot;
}
public String getTrackAmount() {
return this.trackAmount;
}
public void setTrackAmount(String trackAmount) {
this.trackAmount = trackAmount;
}
public String getStorageAmount() {
return this.storageAmount;
}
public void setStorageAmount(String storageAmount) {
this.storageAmount= storageAmount;
}
public String getPrice() {
return this.price;
}
public void setPrice(String price){
this.price = price;
}
}
CDid is a String, so CDid.getCdId() makes no sense at all. You need to go through your entire array to make sure the id doesn't exit.
For instance:
boolean found = false;
for (int i = 0; i < counter; ++i) {
if (cdArray[i].getCdId().equalsIgnoreCase(CDid)) {
found = true;
break;
}
}
if (found) {
System.out.println(CDid + " already exists");
} else if (counter >= cdArray.length) {
System.out.println("The array is full");
} else {
cdArray[counter] = new CD(CDid, CDgenre, CDartist, CDalbum,
CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);
++counter;
}
Also note that you don't need to create the CD unless you know you will be able to add it in the array.
The problem is that you are reading it the wrong way, I assume. As you are dealing with strings, there is no way to separate them from each other without a delimiter, in this case, a newline. You should use Scanner.nextLine, NOT Scanner.next. Scanner.next reads only one character at a time.
Now, for the way you should check for existing ids in the array:
//For loop to check if any of the elements match the CDId. The variable exists will be
//set to true if it already exists in the array.
boolean exists = false;
if(CDId != null) {
for(int i = 0; i < cdArray.length; i++) {
if(cdArray[i] == null) continue;
if(CDId.equalsIgnoreCase(cdArray[i].getCdId())) {
exists = true;
break;
}
}
}
if(exists) {
//If the CDId already exists... (put your own code if you want, such as an error message)
} else {
//If the id doesn't exist in the array yet, add the cd_obj to the array...
boolean added = false;
for(int i = 0; i < cdArray.length; i++) {
if(cdArray[i] == null) {
cdArray[i] = cd_obj;
added = true;
break;
}
}
//if the cd_obj wasn't added to the array, notify the user.
if(!added) {
System.out.println("The array is full");
}
}
So i am trying to make a deal or no deal game the game is not finished yet but the biggest issue i am having is that when i am trying to assign an array list to a array of type cases it seems like it isn't getting assigned.
I tried to debug and after shuffle the output is correct but i am unable to assign the result to the case array so that i can use it in game
Below are my 3 classes upon assigning the outcome i am getting is
The line i am talking about is the method available cases
public class Case {
private int value = 0;
private String face;
/*
* Constructor for type Case
*/
public Case(int value)
{
this.value = value;
}
/*
* Getter and setter methods for instance data
*/
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public String getFace() {
return face;
}
public void setFace(String face) {
this.face = face;
}
}
public class Player {
private String name;
private int age;
private boolean canPlay = false;
private int money = 0;
/*
* Constructor for type Player
*/
public Player(String name, int age) {
super();
this.name = name;
this.age = age;
}
/*
* Getter and Setter methods for all instance Data
*/
public Player(boolean canPlay)
{
this.canPlay = canPlay;
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
public boolean isCanPlay() {
return canPlay;
}
public void setCanPlay(boolean canPlay) {
this.canPlay = canPlay;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
/*
* This method will check if the person playing is at least 18 years old or not
*/
public void checkAge()
{
if(age >= 18)
{
canPlay = true;
System.out.println("Seems like you are old enough to play!");
System.out.println("Let's get started");
}
else
{
canPlay = false;
System.out.println("OH NO! you aren't old enough sadly we won't be able to continue");
}
}
public String toString() {
return "Today's player is "+name+" who is "+age+" old";
}
public static void setupPlayer()throws InputMismatchException
{
String playerName;
int playerAge;
System.out.println("Welcome to the Deal or No Deal game!");
System.out.println("Please state your name:");
Scanner name = new Scanner(System.in);
playerName = name.nextLine();
System.out.println("Welcome "+playerName+" how old are you?");
Scanner age = new Scanner(System.in);
playerAge = age.nextInt();
Player gamePlayer = new Player(playerName, playerAge);
}
public static void Rules()
{
System.out.println("Below listed are the Game Rules\n");
System.out.println("-There are 12 Cases in the game");
System.out.println("-Each case contains a amount of money and you will be "
+ "offered these Cases 1 at a time");
System.out.println("-Upon picking a Case the game will end and you will have a "
+ "chance to walk away with that case");
System.out.println("-If No cases are picked you will get 2 option, to walk away"
+ " with the last Case or take the bankers offer");
System.out.println("-To accept the case type \"Y\" ,to decline it type \"N\"");
}
}
public class SetUpCases {
private Case[] cases = new Case[12];
/*
* This method initializes each object type with an amount which will be the Money in each Case
*/
public void settingUpCases()
{
ArrayList<Integer> myCase= new ArrayList<Integer>();
myCase.add(new Integer(1));
myCase.add(new Integer(50));
myCase.add(new Integer(100));
myCase.add(new Integer(250));
myCase.add(new Integer(500));
myCase.add(new Integer(1000));
myCase.add(new Integer(2500));
myCase.add(new Integer(5000));
myCase.add(new Integer(10000));
myCase.add(new Integer(25000));
myCase.add(new Integer(50000));
myCase.add(new Integer(100000));
/*
* The Shuffle changes which index has what value so game results are different each time played!
*/
Collections.shuffle(myCase);
for(int i = 0; i < cases.length; i++)
{
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(cases[i]);
}
}
/*
* Shows which Cases are still available
*/
public void availableCases()
{
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k]);
}
}
public void startGame()
{
settingUpCases();
}
}
You are printing case object instead of its value.. use getValue (or getFace) method to print the value (or face). For example
for (int k = 0; k < cases.length; k++)
{
System.out.println(cases[k].getValue());
}
If you want to print both value and face, the best way will be to override the toString method and print these variables there.
The reason you are getting those weird values is not because the assignments aren't working but because you aren't printing the string value of your values. Try the following.
for(int i = 0; i < cases.length; i++){
int value = myCase.get(i);
cases[i] = new Case (value);
System.out.println(Arrays.toString(cases[i]));
}
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;
}
so what I did was create 3 classes:
1. Library Class (main)
2. Book Class (which I created an object instance of it on the main class)
3. LibraryException (just to handle exceptions)
However I am puzzled, I cannot figure out how to use the Array with the parameters / settings set in the Book class, here is my program:
public class Library
{
String name;
Book[] books;
int nrBookz = 0;
public Library(String name, int nrBookz) throws LibraryException {
if(nrBookz < 500){
throw new LibraryException();
}
this.name = name;
this.nrBookz = nrBookz;
}
public void addBook(Book Book) throws LibraryException {
if(indexOf(Book) == -1){
if(nrBookz < books.length){
books[nrBookz++] = Book;
}
}
}
private int indexOf(Book Book)throws LibraryException {
for(int i = 0; i < books.length; i++){
if(books[i] == null){
throw new LibraryException("That book does not exist!");
}
else if(books[i].equals(Book)){
return i;
}
}
return -1;
}
public static void main(String[]args) throws LibraryException{
Library b = new Library("Sami Frasheri", 750);
**b.addBook(new Book("Paul Colhen - Alchemist", 138));
b.addBook(new Book("Paul Colhen - Winners Stand ALone", 139));
b.addBook(new Book("Paul Colhen - The river Piedra I sat and I cried", 140));**
}
}
.
public class Book {
String name;
int isbn;
public Book(String e, int iNr) throws LibraryException{
if(e == ""){
throw new LibraryException("Book name is not allowed to be blank / empty!!");
}
else if(iNr < 1 || iNr > 9000){
throw new LibraryException("The isbn is not within the allowed range (1 - 9000)! ");
}
name = e;
isbn = iNr;
}
public boolean equals(Object obj){
if(obj instanceof Book){
Book p = (Book)obj;
return name.toLowerCase().equals(p.getName().toLowerCase());
}
return false;
}
public String getName() {
if(name == null || name == ""){
System.out.print("name (Book) EXCEPTION TO BE ADDED!");
}
return name;
}
public void setname(String name) {
this.name = name;
}
public int getIsbn() {
if(isbn < 0){
System.out.print("ISBN (Book) EXCEPTION TO BE ADDED!");
}
return isbn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
}
So my question is: How can I add (books) or make it possible to be added to the book array? (see blow - after I create the new Library (object of the class Library) *Marked with bold on the main method (Library class)
You are missing the array initialization :
public Library(String name, int nrBookz) throws LibraryException {
if(nrBookz < 500){
throw new LibraryException();
}
this.name = name;
this.nrBookz = nrBookz;
this.books = new Book[nrBookz]; // add this
}
I have an assignment where I have to create three classes, a client class that performs all I/O, a catalog class that maintains a list of catalogItem objects and a catalogItem class that defines a single item in the store's catalog.
I'm trying to start simple at first and create the array and make sure that it is accepting data before I move on to the rest of the assignment. I was able to compile it with no issues but when I am trying to display the array, I get nothing.
import java.util.Scanner;
public class lab3
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
Catalog catalog = new Catalog();
boolean endCatalog = false;
while (!endCatalog)
{
System.out.println("Please choose and option: \n"
+ "1 - Display all items of the catalog\n"
+ "2 - Display an item by keyword\n"
+ "3 - Add an item to the catalog\n"
+ "4 - Remove an item from the catalog\n"
+ "5 - Change the cost of one item in the catalog\n"
+ "6 - Change the cost of all items in catalog by percent\n"
+ "7 - Exit");
int choice = in.nextInt();
switch (choice) {
case 1: System.out.println(catalog.displayAll()); break;
case 2: System.out.println("Display keyword"); break;
case 3: System.out.println("Add item:\nEnter ID: ");
int newId=in.nextInt();
System.out.println("Enter description: ");
String newDesc=in.next();
System.out.println("Enter cost: ");
double newCost=in.nextDouble();
catalog.add(newId, newDesc, newCost); break;
case 4: System.out.println("Remove item"); break;
case 5: System.out.println("Change cost of one item"); break;
case 6: System.out.println("Change cost by %"); break;
case 7: endCatalog=true; break; }
}
}
}
class Catalog
{
final static int MAX = 100;
private CatalogItem[] catalogItems;
int inUse;
public Catalog()
{
catalogItems=new CatalogItem[MAX];
}
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
/*public void remove(int id)
{
}
public String find(String keyword)
{
}
public void changeCost(int id, double percent)
{
}
public void increaseCost(double percent)
{
}
public String toString()
{
}
public boolean equals(Catalog obj)
{
}*/
public String displayAll()
{
String str = "";
for (int i=0; i<inUse; i++) {
str = str + "\n" + catalogItems[i]; }
return str;
}
}
class CatalogItem
{
private int itemID;
private String description;
private double cost;
public CatalogItem()
{
itemID = 1;
description = " ";
cost = 0.0;
}
public CatalogItem(int newID, String newDesc, double newCost)
{
itemID = newID;
description = newDesc;
cost = newCost;
}
public int getItemID()
{
return itemID;
}
public void setItemID(int newID)
{
itemID=newID;
}
public String getDescription()
{
return description;
}
public void setDescription(String newDesc)
{
description=newDesc;
}
public double getCost()
{
return cost;
}
public void setCost(double newCost)
{
cost=newCost;
}
public String toString()
{
return itemID + ", " + description + ", " + cost;
}
public boolean equals(CatalogItem obj)
{
return false;
}
}
Here's the problem:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
What happens to newItem after it is created?
You call this method to add the catalog item:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
But as we can see, this doesn't actually do anything with the object it creates. Did you mean to have this overload of add() call the other one? That would be a good design.
Also, in the other version of add(), you do this:
inUse = 0;
Since you reset inUse every time add() is called, your array will never contain more than one item. Do you see why this is? You should just take this line out.
There is not items ever added to:
private CatalogItem[] catalogItems;
That is so, because you call only this method:
public void add(int newId, String newDesc, double newCost)
{
CatalogItem newItem = new CatalogItem(newId, newDesc, newCost);
}
And that one will never call method that actually tries to add something to the array:
public void add(CatalogItem newItem)
{
inUse = 0;
if(inUse<MAX) {
catalogItems[inUse] = newItem;
inUse++; }
}
In the long run that method will also not work, because item is always added to the index 0. That is so, because as first thing you always set: inUse = 0.