Java - Pass double as arguments without giving actual value - java

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.

Related

What is the relationship between two classes they are tied to a Third class?

Getting stuck with my Travail System Project, Confusing a little bit about understanding that if there Classes called Bookable, Hotel and BookingSystem.
Hotel class is implements Bookable. Furthermore, BookingSystem Class is composition from Bookable, So, I need to create method at BookingSystem class which called addHotel.
what I must do about it to make a relationship between Hotel Class and BookingSystem Class.
Thanks In Advance.
Israa
Hotal Class:
public class Hotel implements Bookable {
private String name, location;
private int noOfRooms;
private double roomPrice;
private Date bookingDate;
private ArrayList<Integer> bookedRooms = new ArrayList<Integer>();
private ArrayList<Integer> numberOfrooms = new ArrayList<Integer>();
public Hotel() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public int getNoOfRooms() {
return noOfRooms;
}
public void setNoOfRooms(int noOfRooms) {
this.noOfRooms = noOfRooms;
}
public double getRoomPrice() {
return roomPrice;
}
public void setRoomPrice(double roomPrice) {
this.roomPrice = roomPrice;
}
public Date getBookingDate() {
return bookingDate;
}
public void setBookingDate(Date bookingDate) {
this.bookingDate = bookingDate;
}
public ArrayList<Integer> getBookedRooms() {
return bookedRooms;
}
public void setBookedRooms(ArrayList<Integer> bookedRooms) {
this.bookedRooms = bookedRooms;
}
public String Book() {
if ( numberOfrooms.size() != (bookedRooms.size())) {
for (int i = 0; i < bookedRooms.size(); i++) {
int oldVal = bookedRooms.get(i);
int newVal = oldVal + 1;
bookedRooms.add(bookedRooms.set(i, newVal));
}
}
return null;
}
}
Bookable class:
public interface Bookable {
public String Book();
}
BookingSytsem Class:
public class BookingSystem {
private ArrayList<Customer> customer = new ArrayList<Customer>();
private ArrayList<Bookable> bookable = new ArrayList<Bookable>();
private ArrayList<Operation> operation = new ArrayList<Operation>();
public BookingSystem() {
}
// **
public void addCustomer(String name, int id) {
Customer customers = new Customer(id, name);
customer.add(customers);
System.out.println("new customer " + customers.getName() + " added");
}
// **
public void deleteCustomer(String name, int id) {
Customer customers = new Customer(id, name);
if (customer.contains(name)) {
customer.remove(name);
}
System.out.println("Customer " + customers.getName() + " deleted");
}
public Customer findCustomer(int id) {
for (Customer c : customer) {
if (c.getId() == id) {
return c;
}
}
return null;
}
public void addHotel() {
Hotel H1 = new Hotel();
Scanner name = new Scanner(System.in);
System.out.println("Please Enter the name of Hotel: ");
String n1 = name.nextLine();
bookable.add(H1);
System.out.println("The Hotel " + name + "added");
}
public void makeABooking(Customer c, Bookable b) {
Scanner input =new Scanner(System.in);
System.out.println("Please Enter your name: ");
String name = input.nextLine();
System.out.println("Please Enter your ID: ");
int ID = input.nextInt();
while(true) {
if(ID == -1 && ID == 0) {
System.out.println("Invalid ID. Enter again: ");
name = input.nextLine();
System.out.println("Please Enter your ID: ");
ID = input.nextInt();
}
}
}
}
(Your question is more suitable to https://softwareengineering.stackexchange.com/ - recommend asking it there...)
General speaking it wouldn't make sense to have a Hotel without a name, location or number of rooms so I'd recommend adding a constructor with minimal required information:
public Hotel (String name, String location, int rooms) {
this.name = name;
this.location = location;
this.noOfRooms = rooms;
}
bookingDate makes no sense as a single property of a hotel but rather a property of each booked room so you have a design issue - this is not addressed here.
Again, roomPrice usually varies by room so in a robust solution this would be a property of a room not a hotel - not addressed here.
Why is there a noOfRooms and a numberOfRooms list. In fact, the numberOfRooms list doesn't make sense as a list. I'd just keep the noOfRooms and get rid of numberOfRooms.
An implied property, nbrOfAvailableRooms can be derived from noOfRooms - bookedRooms.size();
I would assume your bookedRooms is a list of room numbers which are booked but that's not possible to tell from your implementation. You should focus on what you want Book to do.
The Book interface method is not documented but it looks like it should simply take an available asset (room) and consider it booked. It should return a boolean success not a String - especially not null.
I recommend writing (in pseudo code) what you want a Book implementation to do - include that in question. That is the core issue you are having.

JAVA Store Program isn't outputting the correct numbers

I was creating a Java program for my OOP class. The program is supposed to be the start of a store interface and we are going to build off it during the rest of the semester. Whenever I was to add a new product and try to access how much of it is in stock my program says the "Id DNE -1" which is only supposed to print when an id is called and it doesn't exist. I'm not too sure why it's not recognizing the product I just put in. Below are all my classes that are used. I think the error has to be somewhere in my inventory class but I'm not too sure. Any tips or tricks for OOP would greatly be appreciated as well. Cheers
public class main
{
public static void main(String[] args)
{
StoreManager r3 = new StoreManager();
Inventory r4 = new Inventory();
r4.addNewProduct(1,"apple",1.50,50);
System.out.println(r3.qCheck(1));
}
}
public class StoreManager
{
private Inventory store1 = new Inventory();
private Product store2 = new Product();
static Inventory r4 = new Inventory();
public StoreManager(){}
public int qCheck(int id)
{
if (store1.getStock(id) < 0)
{
System.out.println("Id DNE");
return -1;
} else
{
return store1.getStock(id);
}
}
public double dqcheck(int id, int desiredQuantity) {
if (store1.getStock(id) >= desiredQuantity) {
store1.removeStock(id, desiredQuantity);
double cost = store2.getPrice() * desiredQuantity;
return cost;
}
else {
System.out.println("id DNE");
}
return -1;
}
}
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Inventory
{
//Var Declarations
private int quantity;
// FIXME: 2021-02-07 idk if im usin type right
private Product type;
//Hashmap for the data structure in this class using the Product is gonna be a key
// the value is the Integer for the quantity
private Map<Product,Integer> invt = new HashMap<>();
//blank constructor
public Inventory()
{
}
// FIXME: 2021-02-05 Getter and setter methods not really in use
public int getQuantity(){return quantity;}
public Product getType(){return type;}
/*
Used to initialize a new product and its stock into our Hashmap
the Quantity is the Value of our hashmap while we are using the
Product as a whole to be the key
no return type
*/
public void addNewProduct(int id,String name, double price, int quantity)
{
Product product = new Product(name, id, price);
invt.put(product,quantity);
}
/*
Used to get the get for a given id
compares the Id to one of the ids in the Key values to find the product
returns an int for the amount in stock or a -1 as an error if the id doesn't exist
*/
public int getStock(int id)
{
Set<Product> set = invt.keySet(); // Conversion of keys into sets
Iterator<Product> it = set.iterator(); // the only way i could get the code to interate throughout the keys
while (it.hasNext())//Only way i could go through the code
{
type = it.next();// FIXME: 2021-02-07 Idk if type is being used right here but i needed a buffer variable for it to work
Product a = it.next();
if (a.getId() == id)
{
return invt.get(type);//type is an object of Product here so we can use it as a key
}
}
return -1;//representation of error ID Dne
}
/*
Used to add a given Stock for a given Id
void doesnt return anything
assuming inpputed id exists if Dne doesnt do anythin or return an error
*/
public void addStock(int id, int amountToAdd)
{
//Possibly make this hashmap id check into another private method and call
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id)
{
invt.put(type, invt.get(type)+amountToAdd);
return;//exit the function after the addtion is done
}
}
}
/*
Used to remove a given amount of product from stock in reference to a given Id
void doesnt return anythin
assuming id exits otherwise it does nothin
*/
public void removeStock(int id, int amountToRemove)
{
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id && invt.get(type) - amountToRemove >= 0)//checks if the id exits and if there whould be enough stock to remove
{
invt.put(type, invt.get(type)-amountToRemove);
return;
}
}
}
/*
Prints all product information in reference to the id
*/
public void getInfo(int id)
{
Set<Product> set = invt.keySet();
Iterator<Product> it = set.iterator();
while (it.hasNext())
{
type = it.next();
if (type.getId() == id)
{
System.out.println("Name: "+type.getName());
System.out.println("Id: "+type.getId());
System.out.println("Price: "+type.getPrice());
System.out.println("Quantity: "+ invt.get(type)); // FIXME: 2021-02-07 Idk if Quanitity and Id are needed here
}
}
}
}
public class Product
{
private String name;
private int Id;
private double price;
public Product(String Name, int Id,double Price)
{
this.name = Name;
this.Id = Id;
this.price = Price;
}
public Product()
{
}
//Getter Methods
public String getName() {return name;}
public int getId() {return Id;}
public double getPrice() {return price;}
}
public class main
{
public static void main(String[] args)
{
StoreManager r3 = new StoreManager();
r3.store1.addNewProduct(1,"apple",1.50,50);
System.out.println(r3.qCheck(1));
}
}
Use the Inventory object that belongs to StoreManager, that's the only one it can access.

How to format output console columns in java?

I'm made a program that creates an invoice but when it comes numbers in the thousands the output isn't neat and ruins everything. How do I fix this so the program's columns are more aligned with numbers like this? Here is the code I used to create the program. If anyone could help, it would be much appericated.
Here's the one with the main method...
public class InvoicePrinter
{
public static void main(String[] args)
{
Address samsAddress=new Address("Sam's Small Appliances", "100 Main
Street", "Anytown", "CA", "98765");
Invoice samsInvoice =new Invoice(samsAddress);
samsInvoice.add(new Product("Toaster", 29.95),3);
samsInvoice.add(new Product("Hair Dryer", 24.95),1);
samsInvoice.add(new Product("Car Vacuum",19.99),2);
samsInvoice.add(new Product("Nano Parts",100000),1);
samsInvoice.addSimple(new Product("Shipping",5.00));
System.out.println(samsInvoice.format());
}
}
These are the other programs needed for the program to work
import java.util.ArrayList;
public class Invoice
{
public Invoice(Address anAddress)
{
items=new ArrayList<LineItem>();
billingAddress=anAddress;
simpleItems= new ArrayList<SimpleLineItem>();
}
public void addSimple(Product aProduct)
{
SimpleLineItem anItem= new SimpleLineItem(aProduct);
simpleItems.add(anItem);
}
public void add(Product aProduct, int quantity)
{
LineItem anItem=new LineItem(aProduct,quantity);
items.add(anItem);
}
public String format()
{
String r=" I N V O I C E\n\n"+billingAddress.format()+String.format("\n\n%-30s%8s%5s%8s\n","Description", "Price","Qty","Total");
for(LineItem i:items)
{
r=r+i.format()+"\n";
}
for(SimpleLineItem j:simpleItems)
{
r=r+j.format() + "\n";
}
r = r + String.format("\nAMOUNT DUE: $%8.2f", getAmountDue());
return r;
}
public double getAmountDue()
{
double amountDue = 0;
for (LineItem i : items)
{
amountDue = amountDue + i.getTotalPrice();
}
for(SimpleLineItem j:simpleItems)
{
amountDue = amountDue + j.getPrice();
}
return amountDue;
}
private Address billingAddress;
private ArrayList<LineItem> items;
private ArrayList<SimpleLineItem> simpleItems;
}
Few more
public class LineItem
{
public LineItem(Product aProduct, int aQuantity)
{
theProduct = aProduct;
quantity = aQuantity;
}
public double getTotalPrice()
{
return theProduct.getPrice() *quantity;
}
public String format()
{
return String.format("%'-30s%'8.2f%'5d%'8.2f", theProduct.getDescription(),theProduct.getPrice(),quantity,getTotalPrice());
}
private int quantity;
private Product theProduct;
}
Another one
public class SimpleLineItem
{
public SimpleLineItem(Product aProduct)
{
theProduct=aProduct;
}
public double getPrice()
{
return theProduct.getPrice();
}
public String format()
{
return String.format("%-30s" +" " + "%8.2f",
theProduct.getDescription(), theProduct.getPrice());
}
private Product theProduct;
}
Two more
public class Product
{
public Product(String aDescription,double aPrice)
{
description = aDescription;
price = aPrice;
}
public String getDescription()
{
return description;
}
public double getPrice()
{
return price;
}
private String description;
private double price;
}
Last one
public class Address
{
public Address(String aName, String aStreet, String aCity, String
aState,String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = aZip;
}
public String format()
{
return name + "\n" + street + "\n" + city + ", " + state + " " + zip;
}
private String name;
private String street;
private String city;
private String state;
private String zip;
}
Maybe you can take a look at the javadocs by Oracle on System.out.format and DecimalFormat class
Formatting Numeric Print Output
So basically this happens when you cannot decide the total length of your number column until you print out everything. For this you will need to set the number column's length to the lengthiest number or in your case price length and justify right all the numbers. So you'll need to add all the numbers to an array and loop through them to find the lengthiest number.

I keep on getting Cannot find Symbol Error when using Comparable

I keep on getting an error saying Cannot find symbol when trying to compile. The files are both in the same folder, i'm not really sure where i went wrong here.
In this assignment im supposed to write a program that reads a list of employees from a file. The name of the file will be ‘Employee.txt’. The program should output the sorted array to a file called “SortedEmployee.txt”. I already have the Heap class done. Need assistance please.
public class Employee
{
String id;
String name;
String department;
String position;
double salary;
int yos; //Year of Service
//constructor w/ no args
public Employee()
{ salary = 0.0;
id = name = department = position = "";
yos = 0;
}
//constructor w/ args
public Employee(String i, String n, String d, String p, double s, int y)
{
id = i;
name = n;
department = d;
position = p;
salary = s;
yos = y;
}
public void setID(String i)
{ id = i;}
public void setName(String n)
{ name = n;}
public void setDepartment(String d)
{department = d;}
public void setPosition(String p)
{position = p;}
public void setSalary(double s)
{salary =s;}
public void setYOS(int y)
{yos = y;}
public String getID()
{ return id;}
public String getName()
{ return name;}
public String getDepartment()
{return department;}
public String getPosition()
{return position;}
public double getSalary()
{return salary;}
public int getYOS()
{return yos;}
public String toString()
{
String str = "Emplyee Id: " + id + "\nName: " + name +
"\nDepartment: " + department + "\nPosition: " + position
+ "\nSalary: " + salary;
return str;
}
public int compareTo(Employee emp)
{
int idONE = id.compareToIgnoreCase(emp.id);
if (idONE != 0)
return idONE;
return 0;
}
}
public class EmployeeCOMP implements Comparable<Employee>{
#Override
public int compareTo(Employee emp){
return this.id.compareToIgnoreCase(emp.id);
}
}
This is the error I keep on getting.
EmployeeCOMP.java:4: error: cannot find symbol
return this.id.compareToIgnoreCase(emp.id);
^
symbol: variable id
1 error
this refers to the instance of EmployeeCOMP which does not have an id. In this context the compareTo method should be part of the Employee class (not a separate class):
public class Employee {
...
public int compareTo(Employee emp) {
return this.id.compareToIgnoreCase(emp.id); // **this** refers to an Employee instance
}
}
Attempting to use through a separate class suggests you might be needing to implement a Comparator.

Reference of a non static variable

I have class Employe that has variables like id , name ... and 2 other classes that inherit from Employe : Seller and Cashier.
To calculate their salaries, I created a method in each one of Seller and Cashier but I need to access the name via the name getter method in Employe so I'd have :
System.out.println("The salary is "+Seller.getName() +" is : " +salary);
Once I type that, I get an error sayingI need to make the name variable to static, but I need it as non static since I'm creating multiple objects using the name variable.
Any solution to this problem?
EDIT :
This is the Employe class :
public class Employe {
protected int id;
protected String name;
protected String adresse;
protected int nbrHours;
public Employe () {
}
public Employe (int id, String name, String adresse, int nbHours)
{
this.id=id;
this.name=name;
this.adresse=adresse;
this.nbrHours=nbHours;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setNom(String name) {
this.name = name;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
}
This is the Seller class :
public class Seller extends Employe {
private int prime;
public Seller (int id, String name, String adresse, int nbHours,int prime)
{
super(id,name,adresse,nbHours);
this.prime=prime;
}
public int getPrime() {
return prime;
}
public void setPrime(int prime) {
this.prime = prime;
}
#Override
public String toString() {
return super.toString() +" [prime=" + prime + "]";
}
public void salaireSeller ()
{
int salaire = 0;
if(nbrHours<160)
{
salaire = nbrHours * 10 + prime;
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
}
else if(nbrHours >160)
{
int Extra= (160 - nbrHours) * 12;
int salaire1 = 160 * 10000 + prime;
salaire= Extra + salaire1;
System.out.println("La salaire de "+Seller.getName() +" est : " +salaire);
}
}
In the Main class I created a Seller object :
Seller Sel1 = new Seller(2, "Alex", "Miami", 18, 200);
now I want to calculat its salary using the SalaireSeller() method in the Main class of course :
Sel1.salaireSeller();
but in the Seller class :
System.out.println("La salaire de "+Responsable.getName() +" est : " +salaire);
it says I need to set Name to static, this will give every object the same name
You need a Seller instance, to call getName() and getSalary() on.
Seller s = new Seller();
// ...
System.out.println("The salary is " + s.getName() +
" is : " + s.getSalary());
You're certainly trying to access an instance variable from a static method.
What you want to do here is to create an instance of your class, then call the getName() method on the object created.
Seller sell = new Seller();
sell.setName("Jean-Paul"); // This is just an example
System.out.println("His name is " + sell.getName()); // Prints : His name is Jean-Paul
I figuered out a solution, I just need to add the name to the toString() method in class Employee, then add the salary variable to the toString() method in Seller class, without System.out.println(..) in SalaireSeller().
or instead of Seller.getName(), I use this.getName() and it works.

Categories

Resources