Trouble accessing data from java program - java

I'm having a goofy issue. I'm trying to see if I can printout the restaurants and employees data I have here and I can't remember how best to do it this.
Once I can figure out how to do that, I'll be able to create methods using it, but I can't seem to remember how to do it this way.
Updated Code
class Main {
public static void main(String[] args) {
Employee john = new Employee("John","asian",35.00);
Employee sam = new Employee("Sam","Greek",25.00);
Employee michael = new Employee("Michael","Italian",50.00);
Restaurant asian = new Restaurant("Asian","asian",25.00);
Restaurant greek = new Restaurant("greek","greek",25.00);
Restaurant italian = new Restaurant("italian","italian",25.00);
}
public static class Restaurant {
private String restaurantName;
private String cuisine;
private double price;
public Restaurant( String restaurantName,
String cuisine,
double price) {
this.restaurantName = restaurantName;
this.cuisine = cuisine;
this.price = price;
}
public String getRestaurantName() {
return restaurantName;
}
public String getCuisine() {
return cuisine;
}
public double getPrice() {
return price;
}
}
public static class Employee {
private String employeeName;
private String cuisine;
private double budget;
public Employee(String employeeName,
String cuisine,
double budget) {
this.employeeName = employeeName;
this.cuisine = cuisine;
this.budget = budget;
}
public String getEmployeeName() {
return employeeName;
}
public String getCuisine() {
return cuisine;
}
public double getBudget() {
return budget;
}
}
}

For printing out the data of an object you can override the toString method.
After that, the class Restaurant looks like this.
public static class Restaurant {
private String restaurantName;
private String cuisine;
private double price;
public Restaurant( String restaurantName,
String cuisine,
double price) {
this.restaurantName = restaurantName;
this.cuisine = cuisine;
this.price = price;
}
public String getRestaurantName() {
return restaurantName;
}
public String getCuisine() {
return cuisine;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return "Restaurant [restaurantName=" + restaurantName + ", cuisine=" + cuisine + ", price=" + price + "]";
}
}
the class Employee looks like this.
public static class Employee {
private String employeeName;
private String cuisine;
private double budget;
public Employee(String employeeName,
String cuisine,
double budget) {
this.employeeName = employeeName;
this.cuisine = cuisine;
this.budget = budget;
}
public String getEmployeeName() {
return employeeName;
}
public String getCuisine() {
return cuisine;
}
public double getBudget() {
return budget;
}
#Override
public String toString() {
return "Employee [employeeName=" + employeeName + ", cuisine=" + cuisine + ", budget=" + budget + "]";
}
}
and then you can print an object in sysout
System.out.println(michael);

You have to use a toString method() for each Object's class.
For example in Employee Class:
public String toString()
{
String str = "Employee Name: " + employeeName +
"\nCuisine: " + cuisine + "\nBudget: " + budget;
return str;
}
After that you just have to use the toString() in the main() method:
System.out.println(john.toString());
In the main method you could also use an array to store the data and make it easier to access. Then to display both of the objects inside you could use just one for loop, but I used two to keep the outputs separate from one another.
int numEmployees = 3;
Employee myEmployees[] = new Employee[numEmployees];
myEmployees[0] = new Employee("John","asian",35.00); // Stores John in index 0...
myEmployees[1] = new Employee("Sam","Greek",25.00);
myEmployees[2] = new Employee("Michael","Italian",50.00);
// Displays each object who's index is associated with the value for i
for(int i = 0; i < employees.length; i++)
System.out.println(myEmployees[i].toString());
int numRestaurants = 3;
Restaurant myRestaurants = new Restaurant[numRestaurant]
myRestaurants[0] = new Restaurant("Asian","asian",25.00); // Stores Asain in index 0...
myRestaurants[1] = new Restaurant("greek","greek",25.00);
myRestaurants[2] = new Restaurant("italian","italian",25.00);
// Displays each object who's index is associated with the value for i
for(int i = 0; i < restaurants.length; i++)
System.out.println(myRestaurants[i].toString());

Related

How to write an array of objects through composition in another object and how to create them in main class?

For example, there is this program where I could write in the Book object (constructor) many Authors. The errors appear only in main, but there may be some code in other classes, which should be written differently.
```
package ex1;
public class Author {
private String name, email;
private char gender;
public Author(String name, String email, char gender) {
this.name = name;
this.email = email;
this.gender = gender;
}
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
public String getName() {
return name;
}
public void setEmail(String email) {
this.email = email;
}
public char getGender() {
return gender;
}
}
```
In the photo, you can see the program requirements.
```
package ex1;
import java.util.Arrays;
public class Book {
private String name;
private Author[] authors;
private Page page;
private double price;
private int qty = 1;
public Book(String name, Author[] authors, double price) {
this.name = name;
this.authors = authors;
this.price = price;
}
public Book(String name, Author[] authors, Page page, double price, int qty) {
this.name = name;
this.authors = authors;
this.price = price;
this.qty = qty;
this.page = page;
}
#Override
public String toString() {
return "Book [name=" + name + ", authors=" + Arrays.toString(authors) + ", page=" + page + ",
price=" + price + ", qty=" + qty + "]";
}
public String getName() {
return name;
}
public Author[] getAuthors() {
return authors;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
//....
}
```
The class page is working at least.
```
package ex1;
public class Page {
private int pageNumber, numberOfWords;
private String footnote;
public Page(int pageNumber, int numberOfWords, String footnote) {
this.pageNumber = pageNumber;
this.numberOfWords = numberOfWords;
this.footnote = footnote;
}
#Override
public String toString() {
return "Page [pageNumber=" + pageNumber + ", numberOfWords=" + numberOfWords + ", footnote=" +
footnote + "]";
}
public int getPNr() {
return pageNumber;
}
public int getWords() {
return numberOfWords;
}
public String getFoot() {
return footnote;
}
}
```
So here I would like to see that I could create a Book like this or in a similar manner:
Book b2 = new Book("Ac2", authors[authorAna, Kratos], 35);
```
package ex1;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Author authors[] = new Author[2]; // this is a method but it doesn't work as intended
Author authorAna = new Author("Ana", "A#em.com", 'f');
Author Kratos = new Author("Kratos", "K#em.com", 'm');
authors[0] = authorAna;
authors[1] = Kratos;
Page p6 = new Page(6, 400, "He jumped into the haystack to hide from enemies");
Book b1 = new Book("Ac1", authors, 25);
//Book b2 = new Book("Ac2", authorAna, 35);
//Book b3 = new Book("God of War1", Kratos, 20);
//Book b4 = new Book("GoW2", , p6, 20, 40);
System.out.println(Kratos + "\n" + b1.toString());
//System.out.println(b2);
//System.out.println(b3);
//System.out.println(b4);
}
}
```
You can create the Author array like this. Then you would need to index the array to get the individual author object.
Author[] authors = {new Author("Ana", "A#em.com", 'f'),
new Author("Kratos", "K#em.com", 'm')};
Book b1 = new Book("Ac1", authors, 25);
If need be, you could then create a book array the same way or create a book builder.
class Book {
private String name;
private Author[] authors;
private Page page;
private double price;
private int qty = 1;
private Book() {
}
public Book(String name, Author[] authors, double price) {
this.name = name;
this.authors = authors;
this.price = price;
}
public Book(String name, Author[] authors, Page page,
double price, int qty) {
this.name = name;
this.authors = authors;
this.price = price;
this.qty = qty;
this.page = page;
}
#Override
public String toString() {
return "Book [name=" + name + ", authors="
+ Arrays.toString(authors) + ", page=" + page
+ ", price=" + price + ", qty=" + qty + "]";
}
public String getName() {
return name;
}
public Author[] getAuthors() {
return authors;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public static Book bookBuilder() {
return new Book();
}
public Book price(double price) {
setPrice(price);
return this;
}
public Book quantity(int quantity) {
qty = quantity;
return this;
}
public Book name(String name) {
this.name = name;
return this;
}
}
It would be used like this.
Book b = Book.bookBuilder().name("Ac2").price(40.).quantity(20);
Note that you can modify the bookBuilder method to accept any elements of the book class that would always be required. Then you can add whatever methods you need. And the other nice feature of builders is that the order you call the methods doesn't matter (except for the first one of course).

How to iterate to a certain index in a 2D array which is inside an ArrayList?

I want to know how I can iterate to a certain index inside a 2D array, for example how could I fetch the itemQuantity in this code and if there were more than one products how could I fetch all of their quantities.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class practice2 {
public static void main(String[] args) {
List<String[]> inventoryTable = new ArrayList<>();
inventoryTable.add(new String[]{
"Item Name",
"Item Type",
"Quantity",
"Price",
"Expiry Date",
"Date of Purchase"});
String itemName = "oranges";
String itemType = "fruit";
String itemQuantity = "3";
String itemPrice = "2";
String itemExpiryDate = "12/11/2020";
String itemDateOfPurchase = "30/10/2020";
inventoryTable.add(new String[]{
itemName,
itemType,
itemQuantity,
itemPrice,
itemExpiryDate,
itemDateOfPurchase
});
System.out.println(Arrays.deepToString(inventoryTable.toArray()));
}
}
In your case, you have an ArrayList containing String arrays where the third index is the quantity you're looking for.
Using the java "foreach" statement:
//first we iterate through the whole ArrayList obtaining each inventory element
for (String[] inventoryElement : inventoryTable) {
// then we take the third index and we print it out
System.out.println(inventoryElement[3]);
}
Edit: As someone already mention in the comments it's much better to create an object to hold all the information instead of String array.
Example solution:
List<InventoryItem> inventoryTable = new ArrayList<>();
String itemName = "oranges";
String itemType = "fruit";
int itemQuantity = 3;
double itemPrice = 2.0;
String itemExpiryDate = "12/11/2020";
String itemDateOfPurchase = "30/10/2020";
inventoryTable.add(new InventoryItem(itemName, itemType, itemQuantity,
itemPrice, itemExpiryDate, itemDateOfPurchase));
for (InventoryItem inventoryItem : inventoryTable) {
System.out.println(inventoryItem.getPrice());
}
public static class InventoryItem {
private String name, type, expiryDate, dateOfPurchase;
private int quantity;
private double price;
public InventoryItem(String name, String type, int quantity,
double price, String expiryDate,
String dateOfPurchase) {
this.name = name;
this.type = type;
this.quantity = quantity;
this.price = price;
this.expiryDate = expiryDate;
this.dateOfPurchase = dateOfPurchase;
}
public String getName() { return name; }
public double getPrice() { return price; }
public int getQuantity() { return quantity; }
public String getDateOfPurchase() { return dateOfPurchase; }
public String getExpiryDate() { return expiryDate; }
public String getType() { return type; }
#Override
public String toString() {
return "Item: " + name
+ " Type: " + type
+ " Quantity: " + quantity
+ " Price:" + price
+ " Expiry date: " + expiryDate
+ " Date of purchase" + dateOfPurchase;
}
}
You can look at the arraylist as an array. Meaning you can access the indexes [][] but would need to use the get(index)[] instead.
For example how could I fetch the itemQuantity in this code:
inventoryTable.get(1)[2];
would get you the itemQuantity.
And if there were more than one products how could I fetch all of their quantities.
for (int i = 1; i < inventoryTable.size(); i++) {
System.out.println(inventoryTable.get(i)[2]);
}

How do I create an boolean equals method compares objects in an array

My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0 4590.0 2390.0 2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00 4819.50 2390.00 2629.00
Generally, when implementing equals(), you compare “key” fields whose values don’t change for the entity, and don’t compare “state” fields whose values change from time to time.
You are comparing sharePrice, when I believe you should be comparing symbol.
When you do list.indexOf(temp), what that does, right now, is look for a Stock that is equals to the argument passed to it -- so it looks for a Stock with price zero, not caring about the symbol at all. That's what the code does right now.
Honestly, using indexOf and equals is not really appropriate for this problem. indexOf is really only useful when you have something that's totally equal to the target you're looking for.
The best way to do something like this is
Optional<Stock> foundStock = list.stream().filter(stock -> stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
// do something with foundStock.get()
} else {
// no found stock
}
indexOf() is a method return the index of the first occurrence of the specified element in the returned list. If the list does not contain this element, value -1 is returned.
More formally, return the lowest index i that meets the following conditions:
if(o==null? get(i)==null :o.equals(get(i))){
return i;
}
return -1;
If there is no such index, return -1.
And you have override the equals method, I guess you just want to focus on the same price Stock?:
#Override
public boolean equals(Object obj){
if (obj instanceof Stock){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
return false;
}
As my opinion, you have use List<Stock> list so the Object in the list is all Stock. Maybe it could be simplifed:
#Override
public boolean equals(Object obj){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}

Trouble printing objects in ArrayList using Enhanced For Loop

I cannot get the Product Objects to print out anything using an Enhanced for loop. Everything comes out null or 0?
The output show this?
0null0.0This is the id
0null0.0This is the id
0null0.0This is the id
Here's my code:
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
ArrayList < Product > store1 = new ArrayList < Product > ();
store1.add(new Product(3, "Nike", 300.0));
store1.add(new Product(2, "Addidas", 400.0));
store1.add(new Product(6, "Under Armor", 500.0));
for (Product y: store1) {
System.out.println(y + "This is the id");
}
}
}
class Product {
public int id;
public String name;
public double price;
public Product(int startId, String startName, double startPrice) {
startId = id;
startName = name;
startPrice = price;
}
public int getId() {
return id;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public String toString() {
return id + name + price;
}
}
You are doing a backward assignments in the constructor:
public Product(int startId, String startName, double startPrice) {
startId = id;
startName = name;
price = startPrice;
}
leaving the object uninitialized...
but you mean for sure
public Product(int startId, String startName, double startPrice) {
id = startId;
name = startName;
startPrice = price;
}
You have your assignments backward in the constructor. It should be:
public Product(int startId, String startName, double startPrice) {
id = startId; // Not `startId = id;`
name = startName; // Not `startName = name;`
price = startPrice; // Not `price = startPrice;`
}
or better yet (and this would have flagged the problem up for you when you tried to compile), don't rely on implicit this:
public Product(int startId, String startName, double startPrice) {
this.id = startId;
this.name = startName;
this.price = startPrice;
}
You are setting the variables the wrong way around in your constructor, i.e.
startId = id; should be id = startId;
You should also add #Override to your toString() method.

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.

Categories

Resources