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;
}
Related
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.
How do I print the album title from the array-list if the contents of the object is in a private field in another class?
Display Method
public void displayAllAlbums() {
for (int i = 0; i < AlbumList.size(); i++) {
System.out.println(AlbumList.get(i));
}
}
Album Class that has private variables title and price.
class Album {
private String title;
private double price;
Album(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return this.title;
}
public double getPrice() {
return this.price;
}
}
Cart Class adds songs to arraylist can also get total
import java.util.*;
public class Cart {
List<Album> AlbumList = new ArrayList<Album>();
Main Method putting albums into addAlbum method
public static void main(String[] args) {
Cart cart1 = new Cart();
Album album1 = new Album("ye", 20);
Album album2 = new Album("MBDTF", 16);
cart1.addAlbum(album1);
cart1.addAlbum(album2);
System.out.println(cart1.getTotalAlbums());
cart1.displayAllAlbums();
}
adding album to the arralist
public void addAlbum(Album album) {
AlbumList.add(album);
}
Unsure on how to display the album
public void displayAllAlbums() {
for (int i = 0; i < AlbumList.size(); i++) {
System.out.println(AlbumList.get(i));
}
}
Do this.
public void displayAllAlbums() {
for (int i = 0; i < AlbumList.size(); i++) {
Album album = AlbumList.get(i)
System.out.println(album.getTitle() + " "+ album.getPrice());
}
}
Your Arraylist's objects are actually Album object. So when are accessing an ArrayList object via AlbumList.get(i) command, you're getting an Album object instance. So you pass it on to Album variable. Then access the private field via getter methods you've set up earlier!
Cheers!
You can do this either by overriding toString() method in Album class or by providing a public method for displaying the properties.
class Album {
private String title;
private double price;
Album(String title, double price) {
this.title = title;
this.price = price;
}
public String getTitle() {
return this.title;
}
public double getPrice() {
return this.price;
}
#Override
public String toString(){
return "title:"+title+",price:"+price;
}
}
While you passing the object to System.out.println(AlbumList.get(i)), the toString() method will get invoke and print album title and price.
How do I print the album title from the array-list
Just use the public accesor method i.e. Album#getTitle()
public void displayAllAlbums() {
for (Album album : AlbumList) {
System.out.printf("Album title: %s%n",album.getTitle());
}
}
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 );
}
}
I hope you can help me.
I'm working on a "Introduction to programming" Java-project for school, and have a little problem with inheritance.
I need to create methods for adding different products to an arraylist, that represents a very simple database. And so, i have an arraylist for cupcakes, one for bread etc.
How can I create a method in my superclass 'Product', that all the subclasses can inherit.
Right now the 'Add product' is implemented in every subclass, and looks something like this.
protected void addCakes() throws IllegalArgumentException {
System.out.println("Enter quantity to be added: ");
int n = scanner.nextInt();
if(n > 0) {
for(int i = 0; i < n; i++) {
cupcakedatabase.addCupcake(this);
}
} else {
throw new IllegalArgumentException("The amount has to be positive");
}
}
and the code in the cupcakeDB looks likes this:
private static ArrayList<Cupcake> cupcakes;
public CupcakeDB() {
cupcakes = new ArrayList<Cupcake>();
}
public void addCupcake(Cupcake cupcake) {
cupcakes.add(cupcake);
}
EDIT
This in my product class.
import java.util.Scanner;
public abstract class Product {
protected String name;
protected String flavor;
protected double price;
protected int quantity;
Scanner scanner = new Scanner(System.in);
public void createProduct(String name, String flavor, double price) {
this.name = name;
this.flavor = flavor;
this.price = price;
}
public void changePrice(double price) {
this.setPrice(price);
}
public void changeFlavor(String flavor) {
this.setFlavor(flavor);
}
public void setFlavor(String flavor) {
this.flavor = flavor;
}
public void setPrice(double price) {
this.price = price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setName(String name) {
this.name = name;
}
public String getFlavor() {
return flavor;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
}
you can try Something like,
class Product<T>{
ArrayList<T> list = new ArrayList<T>();
public void add(T t){
list.add(t);
}
public ArrayList<T> getMyAllProduct(){
return list;
}
}
Now Inherit this to your specific Product class and will get you it automatic.
This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.