toString method and searching a list for string equality - java

This is an Object Oriented program with two classes Catalog and Products that reads a file that contains the product name, quantity, and price, adds them to a list array, and calculate the total Price of the items. Everything works with my program except that it has a toString method that when I ran the program it prints something like this #445ea7e I think this happens because the addProducts() and getProducts(String name) on the Catalog class has to do something with the toString() and I don't know how to connect them to work.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Catalog{
private static int MAX_ITEMS = 10;
/**
* List of Products objects.
*/
private Products[] list;
private int nextItem;
/**
* Default constructor
*/
public Catalog(){
list = new Products[MAX_ITEMS];
nextItem = 0;
}
/**
* Adds an item to the list
*/
public void addProducts (String name, int quantity, double price){
**//I tried this: list[nextItem] = new Products(name, quantity, price);
//but I'm not sure if that's ok.**
}
/**
* 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
*/
public Products getProducts(String name){
**//search a list for string equality using the name of the product and returns 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.println(toString()); **I don't know how to call toString**
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
}
This is the Products class with the toString() method.
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(){
String s=null;
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
}
This is the file with the Products information
Football 2 15.50
ChapStick 1 3.87
Book 4 10.00

You add toString() to your Catalog class as Product class :
public class Catalog {
private static int MAX_ITEMS = 10;
/**
* List of Products objects.
*/
private Products[] list;
private int nextItem;
// your old code here
// new code
#Override
public String toString() {
return "this is a catalog";
}
}
You call catalog.toString():
public static void main(String[] args)
throws FileNotFoundException {
Catalog catalog= new Catalog();
catalog.loadList(args[0]);
System.out.println();
//System.out.println(toString()); **I don't know how to call toString**
// use this line
System.out.println(catalog.toString());
System.out.println();
System.out.format("Total Price = %9.2f\n", catalog.getTotalPrice());
}
In your toString() method of Product class. you should change initialize variable from s=null; to s="";. Here is sample :
public String toString(){
String s="";
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}
Hope this help :)

In your toString() method (in products class), change
String s = null;
to
String s = "";
Also, you have to make a toString method for the Catalog class in order to call it.
An example toString method for catalog class can be:
public String toString(){
String toReturn = "";
for(Products current: list){
toReturn+=current.toString()+"\n";
}
return toReturn;
}
Then if main just call, System.out.println(catalog.toString());

Try adding override to your toString method this might be the solution base on your current output.
#Override
public String toString(){
String s=null;
s+=getName();
s+=s + " ";
s+=getQuantity();
s+=s + " ";
s+=getPrice();
return s;
}

Related

Java - Reading text file and storing it in an objects inside a class

I have a super class and 2 subclasses.
My super class is "Employee" with a name and monthlySalary.
My 1st subclass is "Salesman" with an additional instance variable called annualSales.
My2nd subclass is "Executive" with an additional instance variable called called stockPrice.
I have a text file that includes
"year, firstname,lastname, monthlySalary"
"year, firstname,lastname, monthlySalary, annualSales"
"year, firstname,lastname, monthlySalary, stockPrice"
Big question: How do I store the information from my text file into my superclass and two subclasses?
I have this in my main method. After some tips here I tried updating it. Again thank you for the help, I am trying to understand this to succeed. I am very new to programming in general.
public class Project1 {
/**
* #param args the command line arguments
* #throws java.io.FileNotFoundException
*/
public static void main(String[] args) throws IOException {
FileReader fr =new FileReader("C:\\Users\\JakobJundi\\Documents\\NetBeansProjects\\Project1\\src\\project1\\information.txt");
BufferedReader br =new BufferedReader(fr);
String fileLine;
fileLine = br.readLine();
String[] fields = fileLine.split(" ");
Employee employee1 = new Employee(fields[0],Double.parseDouble(fields[1]));
//Salesman salesman1 = new Salesman (fields[0], Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
//Executive executive1 = new Executive (fields[0], Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
System.out.println(employee1);
//System.out.println(salesman1);
//System.out.println(executive1);
fields = fileLine.split(" ");
if (fields.length == 2){
Salesman salesman1 = new Salesman(fields[0], Double.parseDouble(fields[1]), Double.parseDouble(fields[2]));
System.out.println(salesman1);
}
}
}
This is my Employee super class:
public class Employee {
final String name;
final double monthlySalary;
private double annualSalary;
public Employee(String name, double monthlySalary) {
System.out.println("Constructing an Employee");
this.name = name;
this.monthlySalary = monthlySalary;
}
#Override
public String toString() {
return "Name: " + name + "--" + "Monthly salary: " + monthlySalary;
}
//getters
public String getName() {
return name;
}
public double getMonthlySalary() {
return monthlySalary;
}
public double getAnnualSalary(){
return monthlySalary * 12;
}
//setters
public void setannualSalary(double newannualSalary) {
annualSalary = newannualSalary;
}
}
And this is one out of my 2 subclasses.
public class Salesman extends Employee {
private final double annualSales; // Annual sales
private double annualSalary;
public Salesman(String name, double monthlySalary, double annualSales) {
super(name, monthlySalary);
this.annualSales = annualSales;
System.out.println("Constructing a Salesman");
}
#Override
public String toString() {
return "Name: " + name + "--" + "Monthly salary: " + monthlySalary;
}
public double getAnnualSales() {
return annualSales;
}
#Override
public double getAnnualSalary(){
return (monthlySalary * 12) + (annualSales * 0.02);
}
#Override
public void setannualSalary(double newannualSalary) {
annualSalary = newannualSalary;
}
}
When running this I get this output:
Constructing an Employee
Name: Jundi,jakob--Monthly salary: 2000.0
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at project1.Project1.main(Project1.java:49)

Java: How would I declare an undefined number of object with user inputted data?

for my assignment I am suppose to have a user input the name and price of items. However, they are to enter in an unlimited amount of times until a sentinel value is used. I don't actually know how I'd go about doing this. The only way I know how to declare an object with user input is to use a scanner and then place that data within the arguments of a constructor. But that would only create a single object. Thanks!
import java.util.Scanner;
public class Item
{
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
private String name;
private double price;
public static final double TOLERANCE = 0.0000001;
public Item(String name,double price)
{
this.name = name;
this.price = price;
}
public Item()
{
this("",0.0);
}
public Item(Item other)
{
this.name = other.name;
this.price = other.price;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public void setName(String name)
{
this.name = name;
}
public void setPrice(double price)
{
this.price = price;
}
public void input(String n, double item)
{
}
public void show()
{
// Code to be written by student
}
public String toString()
{
return "Item: " + name + " Price: " + price;
}
public boolean equals(Object other)
{
if(other == null)
return false;
else if(getClass() != other.getClass())
return false;
else
{
Item otherItem = (Item)other;
return(name.equals(otherItem.name)
&& equivalent(price, otherItem.price));
}
}
private static boolean equivalent(double a, double b)
{
return ( Math.abs(a - b) <= TOLERANCE );
}
}
As I understood you want just initialize an array of obects.
Firstly you need initialize an array:
int n = scanner.nextInt(); // you may get n in other way
Item[] items = new items[n];
Then you can fill it with new instances of Item:
for(int i = 0; i < n; i++){
items[i] = new Item(); //constructor args may be here
}
To add undefined number of object best choice is List in java. By using your example i add some code in main() method as below :
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
List<Item> items = new ArrayList<>();
while (true) {
System.out.println("--------------------------------");
System.out.print("Enter item name :: ");
String name = input.next();
System.out.print("Enter item price :: ");
while (!input.hasNextDouble()) {
System.err.println("Invalid Price (Double) eg. 300");
System.out.print("Enter item price :: ");
input.next();
}
double price = input.nextDouble();
Item item = new Item(name, price); //creating object by passing value in constructor
items.add(item); //adding object in list
System.out.println("Do you want to add more items ? 'Y'=>Yes or 'N'=>No ");
String ans = input.next();
if ("N".equalsIgnoreCase(ans)) {
break;
}
}
//To retrive item object list
for (Item i : items) {
System.out.println(i);
}
}

Java - Pass double as arguments without giving actual value

Got an error at : Movie m = new Movie(id, name, cost);
"cannot find symbol - var cost"
cost is set only when user insert input and cannot put actual value e.g.200.00
What should I put as argument?
Also, Session can only be created if user enters correct movie ID.
How do I match compare input(int) to an array?
Any help will be appreciated. Explanation is also important for me
Movie Class:
private void addMovie()
{
System.out.println("Setup a Movie");
int id = movies.setId();
String name = In.readString("Enter Movie Name: ");
double cost = In.readDouble("Enter Movie Cost:" );
Movie movie = new Movie(id, name, cost);
movies.add(movie);
menu();
}
Session Class:
private void addSession()
{
System.out.println("Add a Session");
int id = sessions.setId();
String name = In.readString("Enter Session Name: ");
int movieId = In.readInt("Enter Movie id:" );
**//match input with id array**
int theatreId = In.readInt("Enter Theatre id:" );
**//match input with theatre id array**
String sessionTime = In.readString("Enter Session Time - 0 for 9am, 1 for 12noon, 2 for 3pm or 3 for 6pm: ");
double GoldSeatsPrices = In.readDouble("Enter Prices fro Gold Class Seats:");
double ReguSeatsPrices = In.readDouble("Enter Prices for Regular Seats:");
Movie m = new Movie(id, name, cost);
Session session = new Session(id, name, m);
sessions.add(session);
menu();
}
Movie Class:
public class Movie extends Record
{
private double cost;
public Movie(int id, String name, double cost)
{
super(id, name);
this.cost = cost;
}
public double getCost()
{
return cost;
}
public String toString()
{
return "Movie: "+ super.toString() + " cost: $"+ cost;
}
}
Records Class: (super.):
import java.util.*;
/**
* class Records - complete
*/
public class Records
{
protected LinkedList<Record> records = new LinkedList<Record>();
protected int id = 0;
protected Record find(int id)
{
for(Record record: records)
{
if (record.matches(id))
return record;
}
return null;
}
protected void add(Record record)
{
records.add(record);
}
public int size()
{
return records.size();
}
public void show()
{
System.out.println(toString());
}
public String toString()
{
String str = "";
for(Record record : records)
str += record.toString() + "\n";
return str;
}
}
Record:
/**
* class Record - complete
*/
public class Record
{
protected int id;
protected String name;
public Record(int id, String name)
{
this.id = id;
this.name = name;
}
public String getName()
{
return name;
}
public int getId()
{
return id;
}
public boolean matches(int id)
{
return this.id == id;
}
public String toString()
{
return id + " " + name;
}
}
To the first question: There is no variable cost within addSession(). If you have not defined an attribute cost within Session then this is the problem.
To the second question: I am not quite sure that I understand your problem correctly. You have an int[] values and want to know, whether a given int x is within that array? If so, you can achieve this with this code snippet:
for (int value : values) {
if (value == x) {
// Put code, that should be executed when the value is found, here
}
}
Can you place the Super class Record also in your question?
Probably, you need to check the super constructor, which is differing from your sub class constructor.

How can I search through a scanner and divide a String by spaces?

I am trying to construct a store by reading items from a given Scanner. The constructor must repeatedly (until item name is *) read items from the given scanner object and add it to its inventory.
BreadLoaf 2.75 25
I need to divide a string like this into "Breadloaf" "2.75", and "25". And then go to the next line and do the same thing until it reads "*"
public class Store {
private ArrayList<Item> inventory;
// CONSTRUCTORS
/*
* Constructs a store without any items in its inventory.
*/
public Store() {
}
/*
* Constructs a store by reading items from a given Scanner. The constructor
* must repeatedly (until item name is *) read items from the given scanner
* object and add it to its inventory. Here is an example of the data (that
* has three items) that could be entered for reading from the supplied
* scanner:
*/
public Store(Scanner keyboard) {
while(keyboard != null){
}
}
Try below code. it works I have recently checked.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class MyClient {
public static void main(String args[]) {
List<Item> inventory = new ArrayList<Item>();
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s1 = sc.nextLine();
if (s1.equals("*")) {
break;
} else {
Scanner ls = new Scanner(s1);
while (ls.hasNext()) {
Item item = new Item(ls.next(), ls.nextFloat(), ls.nextInt());
inventory.add(item);
}
}
}
System.out.println(inventory);
}
}
Now you need to create an Item.java below is Item .java
public class Item {
private String name;
private int quanity;
private float price;
public Item(String name, float price, int quanity) {
this.name = name;
this.price = price;
this.quanity = quanity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getQuanity() {
return quanity;
}
public void setQuanity(int quanity) {
this.quanity = quanity;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
#Override
public String toString() {
return "Item [name=" + name + ", quanity=" + quanity + ", price="
+ price + "]";
}
}
After typing all the inventory type "*"(star) at the end it will list all the entered Items .

adding array objects to a list

i'm new to java and I am having problems adding my array objects to my list. I have already checked the topics in this forum but can't find something similar to my problem.
I have already made a class called Item that will save information about an item to be sold, and it has 4 instance variables id, desc, cost, quantity. And then I have a Sales class which has my main method. Basically what I want to do is build an array of objects from my Item class and hard code my data(which I have already created, i'm not sure if I did it right though).
I have created an ArrayList and what I want to do now is add the 5 objects from the array that I created into the list.
This is my Item class
public class Item {
private String itemID;
private String desc;
private double cost;
private int quantity;
public Item() {
itemID="";
desc="";
cost=0;
quantity=0;
}
public Item(String id, String d, double c, int q) {
itemID = id;
desc = d;
cost = c;
quantity = q;
}
/**
* #return the itemID
*/
public String getItemID() {
return itemID;
}
/**
* #param itemID the itemID to set
*/
public void setItemID(String itemID) {
this.itemID = itemID;
}
/**
* #return the desc
*/
public String getDesc() {
return desc;
}
/**
* #param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* #return the cost
*/
public double getCost() {
return cost;
}
/**
* #param cost the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
/**
* #return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* #param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Item [itemID=" + itemID + ", desc=" + desc + ", cost=" + cost
+ ", quantity=" + quantity + "]";
}
}
And my Sales class:
import java.util.*;
public class Sales {
/**
* #param args
*/
public static void main(String[] args) {
int i;
Item[] items = new Item[5];
for(i = 0; i < items.length; i++)
{
items[i]= new Item(); // create array
}
//hard-coded values of id, desc, cost, qty
items[0].setItemID("PN250");
items[1].setItemID("ER100");
items[2].setItemID("PP150");
items[3].setItemID("MK200");
items[4].setItemID("PN300");
items[0].setDesc("Pen");
items[1].setDesc("Eraser");
items[2].setDesc("Paper");
items[3].setDesc("Marker");
items[4].setDesc("Pen");
items[0].setCost(1.50);
items[1].setCost(1.25);
items[2].setCost(3.75);
items[3].setCost(2.50);
items[4].setCost(2.25);
items[0].setQuantity(0);
items[1].setQuantity(175);
items[2].setQuantity(310);
items[3].setQuantity(75);
items[4].setQuantity(450);
double total = 0;
for(Item d : items)
{
System.out.print(d.getItemID());
System.out.print("\t" + d.getDesc());
System.out.print("\t" + d.getCost());
System.out.println("\t" + d.getQuantity());
}
List<Item> obj;
obj = new ArrayList<Item>();
}
}
You could add the array into your list with the following:
obj.addAll(Arrays.asList(items));
You can use:
for (i = 0; i < items.length; i++)
{
obj.add(items[i]);
}
but why not add the items as soon as they are created & populated?
instead of creating an array at the beginning of your function, create an arrayList and add objects to it using the put method.
Also, you should think of making your objects immutables and pass their attributes to their constructor instead of calling the setter for each attribute

Categories

Resources