Create random objects from a Product class [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I have a Product class that represent a Product:
import java.util.ArrayList;
public class Product {
private int productId;
private String productType;
private String brand;
private double price;
public Product(int productId, String productType, String brand, double price)
{
this.productId = productId;
this.productType = productType;
this.brand = brand;
this.price = price;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getBrand() {
return this.brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
}
Now, in my program, I want to create 3 random objects of this Product class, and here is my code for that:
public static void main(String[] args) {
ArrayList<Product> products = new ArrayList();
Random r = new Random();
for(int i = 0; i < 3; i++)
{
products.add(new Product(1337, "Type", "Brand", 300.33));
}
}
Now, my question is how do I implement so that the random class creates random values? I have created static values for the products, so how do I randomize it so I get 3 different values?

Without knowing which element of Product you want to randomize, one can only keep guessing. The code given below is not the solution to your question; rather, it is to give you a pointer about how you can use the randomly generated values:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Product {
private int productId;
private String productType;
private String brand;
private double price;
public Product(int productId, String productType, String brand, double price) {
this.productId = productId;
this.productType = productType;
this.brand = brand;
this.price = price;
}
public int getProductId() {
return this.productId;
}
public void setProductId(int productId) {
this.productId = productId;
}
public String getProductType() {
return this.productType;
}
public void setProductType(String productType) {
this.productType = productType;
}
public String getBrand() {
return this.brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return this.price;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Product [productId=" + productId + ", productType=" + productType + ", brand=" + brand + ", price="
+ price + "]";
}
public static void main(String[] args) {
List<Product> products = new ArrayList<>();
Random r = new Random(10);
int num;
for (int i = 0; i < 3; i++) {
num = r.nextInt(10);
products.add(new Product(r.nextInt(10000), "Type" + num, "Brand" + num, 1000 * r.nextDouble()));
}
products.stream().forEach(System.out::println);
}
}
A sample run:
Product [productId=2380, productType=Type3, brand=Brand3, price=257.8027905957804]
Product [productId=1456, productType=Type6, brand=Brand6, price=244.11725056425314]
Product [productId=6214, productType=Type1, brand=Brand1, price=370.6111260136414]
Feel free to comment should you need any further help.

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

Trouble accessing data from java program

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

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 do I call a method from a parent of a parent of an inherited class? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
public class TimsOrder {
private int size;
private String name;
private static TimsProduct[] items;
private TimsOrder(String name, int size) {
this.name = name;
this.size = size;
}
#Override
public double getRetailPrice(){
return price;
}
private static void orderItem(TimsProduct item) {
Donut chocolate = Donut.create();
item = chocolate;
}
public static TimsOrder create() {
items = new TimsProduct[size];
for (int i = 0; i < items.length; i++) {
orderItem(items[i]);
}
TimsOrder order = new TimsOrder("OrderName", 1); //Where 1 is the # of items
}
public double getAmountDue() {
double total = 0;
System.out.println("Testpoint");
for (int i = 0; i < items.length; i++) {
total = total + (((TimsProduct) items[i]).getRetailPrice()); //Line with issue
}
return total;
}
}
public abstract class TimsProduct extends Commodity {
private String name;
private double cost;
private double price;
#Override
public double getRetailPrice(){
System.out.println("Testpoint2");
return price;
}
}
public class Donut extends TimsProduct {
private String description;
private int calorieCount;
private Donut(String name, String description, double cost, double price, int calorieCount) {
super(name, cost, price);
this.description = description;
this.calorieCount = calorieCount;
}
public static Donut create() {
Donut chocolate = new Donut("Chocolate", "Glazed", 0.30, 0.99, 500);
return chocolate;
}
}
Test Code:
TimsOrder t = TimsOrder.create();
System.out.println(t);
System.out.printf("Total Price: $%.2f\n", t.getAmountDue());
I realize that t.items has 0 values which is the problem here. What I do not know is why these values are not there.
If anyone wants to see the files:
Commodity.java
https://pastebin.com/raw/9sWbDWV8
TimsProduct.java extends commodity
https://pastebin.com/raw/jzgfkd0P
TimsOrder.java
https://pastebin.com/raw/vc0VtDq6
Donut.java extends TimsProduct
https://pastebin.com/raw/w7iEQG1H
This is an initial response based on what little the OP provided.
You are not overriding your getters in your deriving classes (and the basic implementation in the base can not compile) :
public abstract class Commodity {
public double getProductionCost() {
// no return value!
}
public double getRetailPrice() {
// no return value!
}
}
public abstract class TimsProduct extends Commodity{
private String name;
private double cost;
private double price;
public TimsProduct(String name, double cost, double price){
this.name = name;
this.cost = cost;
this.price = price;
}
public String getName(){
return name;
}
// no #Override!
public double getProductionCost(){
return cost;
}
// no #Override!
public double getRetailPrice(){
return price;
}
public String toString(){
return ("Name is: " + name + "cost is: " + cost + "price is: " + price );
}
}

NullPointerException in my function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
Good day to everyone
I'm new here and in Java, and this is one of first programs with 4 classes and simple methods.
In this prog we put our deal from keybord(we put buyer, seller names, title, price and quantity of products buyed). And so, after I input 2 deals and program must give output I get NullPointerException.
Application.java
package ua.lviv.my;
import java.util.Scanner;
public class Application {
private static Deal [] deal = new Deal[2];
public static void main(String[] args) {
new Application().allActions();
}
void allActions(){
input();
System.out.println("======================");
output();
}
public void output(){
for(int i=0; i<deal.length; i++){
System.out.println("Buyer :" +deal[i].getBuyer().getName());
System.out.println("Seller :" +deal[i].getSeller().getName());
for (int j = 0; j < deal[i].getProducts().length; j++) {
System.out.println("Buys " +deal[i].getProducts()[j].getTitle() +"for " +deal[i].getProducts()[j].getPrice() + " in quantity " +deal[i].getProducts()[j].getQuantity());
}
}
}
public void input(){
for (int i=0; i<deal.length; i++){
deal[i]=inputDeal();
}
}
public Members inputMember(String msg){
Members members = new Members();
String memberName = keybordIn(msg);
members.setName(memberName);
return members;
}
public Product inputProduct(){
Product product =new Product();
String titleStrng = keybordIn("Enter product title");
String priceStrng = keybordIn("Enter product price");
String quantityStrng = keybordIn("Enter quantity");
double price=Double.parseDouble(priceStrng);
int quantity = Integer.parseInt(quantityStrng);
product.setTitle(titleStrng);
product.setPrice(price);
product.setQuantity(quantity);
product.getCost(price, quantity);
return product;
}
public Deal inputDeal(){
Members buyer = inputMember("Enter buyer name :");
Members seller =inputMember("Enter seller name :");
Product [] products = new Product[2];
for(int i=0; i<products.length; i++){
products [i]=inputProduct();
}
Deal deal = new Deal(buyer, seller, products);
return deal;
}
public String keybordIn(String msg){
System.out.println(msg);
Scanner scan = new Scanner(System.in);
String in = scan.next();
return in;
}
}
Deal.java
package ua.lviv.my;
import java.util.Date;
public class Deal {
private Date date = new Date();
private Members buyer;
private Members seller;
private Product[] products = new Product[2];
public Deal(Members buyer, Members seller, Product[] products) {
}
public Date getDate() {
return date;
}
public Members getBuyer() {
return buyer;
}
public Members getSeller() {
return seller;
}
public Product[] getProducts() {
return products;
}
public double inTotal() {
double summ = 0;
for (int i = 0; i < products.length; i++) {
summ += products[i].getCost(products[i].getPrice(),
products[i].getQuantity());
}
return summ;
}
}
Members.java
package ua.lviv.my;
public class Members {
String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package ua.lviv.my;
public class Product {
private String title;
private double price;
private int quantity;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public double getCost(double price, int quantity){
double cost = price*quantity;
return cost;
}
}
Start by taking a look at the constructor for Deal...
public Deal(Members buyer, Members seller, Product[] products) {
}
You never assign any of the values passed via the constructor to the member fields, for example...
public Deal(Members buyer, Members seller, Product[] products) {
this.buyer = buyer;
this.seller = seller;
this.products = products;
}

Categories

Resources