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.
Related
public class Student {
private String name;
private long id;
private String grade;
private int[] test;
private int NUM_TESTS;
public Student(){
name="Un";
id=0;
grade="Un";
test=new int[0];
NUM_TESTS=5;
}
public Student(String x, long z) {
name=x;
id=z;
}
public void setName(String n) {
name=n;
}
public void setID(long i) {
id=i;
}
public void setGrade(String g) {
grade=g;
}
/*public void setTestScore(int t,int s) {
test=t;
test=s;
}
public int getTestScore(int) {
return test;
}*/
public int getNumTests() {
return NUM_TESTS;
}
public String getName() {
return name;
}
public long getID() {
return id;
}
public String getGrade() {
return grade;
}
public String toString() {
return getTestScore()+getNumTests()+getName()+getID()+getGrade();
}
/*public void calculateResult() {
int sum=0;
for (int t:test)sum+=t;
double average= 1.0t*sum/5;*/
}
}
Here is my code I have spaced out the places where I am having the issues. I am writing a Student subclass with subclasses undergrad and postgrad.
Here is the UML
I don't understand how to correctly implement testScore if it is not one of the variables? Nevermind the calculate result I'll fix that myself. I am also unsure if my constructors are accurate. All the students do five exams that's a constant
setTestScore(int t, int s)... I do recommend to use carefully chosen names (identifiers). For example if you just rename the parameters to: setTestScore(int testNumber, int score) you can be more familiar what should you inplement.
test = new int[0];isn't what you want. You want test = new int[NUM_TESTS]
Try to reconsider method setTestScore(int testNumber, int score)
first parameter is actually the index in the array of test and the second is the value.
So, your method should be something like this:
public void setTestScore(int testNumber, int score) {
test[testNumber] = score;
}
I just gave you some guidance for your own implementation...
First of all, It seems that Student class should be abstract. because each student is UnderGraduate or PostGraduate.
Secondly, you should extend the child classes from Student class.
I hope the below code be helpful:
abstract class Student {
private String name;
private long id;
private String grade;
private int[] test;
private final int NUM_TESTS = 5;
public Student(){
name = "UN";
id = 0;
grade = "UN";
test = new int[NUM_TESTS];
}
public Student(String name, long id){
this.name = name;
this.id = id;
}
#Override
public String toString() {
//TODO: write your desire toString method
return getNUM_TESTS()+getName()+getId()+getGrade();
}
abstract void claculateResult();
public int getTestScore(int testNumber){
if(testNumber >= NUM_TESTS)
return 0;
return test[testNumber];
}
public void setTestScore(int testNumber, int score){
if(testNumber >= NUM_TESTS)
return;
test[testNumber] = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
public int[] getTest() {
return test;
}
public void setTest(int[] test) {
this.test = test;
}
public int getNUM_TESTS() {
return NUM_TESTS;
}
}
and the UnderGraduate class would be:
public class UnderGraduate extends Student{
public UnderGraduate(){
}
public UnderGraduate(String name, long id){
super();
}
#Override
void claculateResult() {
//TODO: DO whatever you want
}
}
remember that the PostGraduate class is same as UnderGraduate.
I have an array list that is made up of different types. I want to use the get method in the array list to extract only one element from a specified index
public BookCollection() {
collection = new ArrayList<Book>(10);
}
public void addbook(String title, String author, int year, double cost, boolean Available) {
Book a = new Book(title, director, year, cost, Available);
collection.add(a);
}
In the above code I want to create a library of books but then at some point I only want the title.
public static void main(String[] args) {
BookCollection library = new BookCollection();
library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);
System.out.println(collection.get(0).toString())
}
Then I want to get just the title. So in this case it would be Pride & Prejudice. At the moment the out output is "Pride & PrejudiceJane Austen180124.95"
But I want it to be just "Pride & Prejudice".
collection.get(0).getTitle()
?
Gygabyte's answer is right. You should create getter methods in your Book class for every field, so you can call separately whenever you want.
You should also check Java rules and conventions, in this particular case, variable and method names should start with a lowercase letter, so you should switch from "Available" to "available".
Uppercase letters are for Classes.
I tried your code and found a solution, hope it will be right for you:
This is BookCollection class:
public class BookCollection extends ArrayList<Book>{
private static final long serialVersionUID = 1L;
private ArrayList<Book> collection;
public BookCollection() {
this.collection = new ArrayList<Book>();
}
public void addbook(String title, String author, int year, double cost, boolean available) {
Book a = new Book(title, author, year, cost, available);
this.add(a);
}
public static void main(String[] args) {
BookCollection library = new BookCollection();
library.addbook("Pride & Prejudice", "Jane Austen", 1801, 24.95, true);
System.out.println(library.get(0).isAvailable());
}
}
And this is Book class, with getters and setters:
public class Book {
private String name;
private String author;
private int year;
private double cost;
private boolean available;
public Book(String name, String author, int year, double cost, boolean available){
this.name = name;
this.author = author;
this.year = year;
this.cost = cost;
this.available = available;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public double getCost() {
return cost;
}
public void setCost(double cost) {
this.cost = cost;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
}
I want to search recipe which match with shopping list items and it will suggest recipe to user based on most important ingredients like in Banana MilkShake {milk and banana} could make banana milkshake alone {sugar and vanilla} are optional,if I add items on shopping list like {banana,milk} it will search recipe on the basis of these ingredients rather {banana,milk,sugar and vanilla}
for example:
Banana Milk Shake Ingredients:
**Ingredient Name
1.banana (important)
2.milk (important)
3.vanilla (optional/not important)
4.sugar (optional/not important)
**Shopping List**
banana
milk
egg
rice
We could also make Banana Milkshake without sugar and vanilla so important ingredients will be milk and banana.
public class Ingredient implements Serializable{
private String name;
private String quantity;
public Ingredient(){
}
public Ingredient(String name,String quantity){
this.name=name;
this.quantity=quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
}
and my working code:
public Set<Recipe> searchByIngredient(List<ShoppingList> shop, List<Recipe> list) {
int matchedItems = 0;
Set<Recipe> result = new HashSet<Recipe>();
for (Recipe rn : list) {
boolean recipeMatched = false;
for (ShoppingList r : shop) {
for (int i = 0; i < rn.getIngre().size(); i++) {
if (rn.getIng(i).contains(r.getName())) {
matchedItems++;
int temp = matchedItems;
if(temp >= 2){
result.add(rn);
recipeMatched = true;
}
}
if (recipeMatched)
break;
}
if (recipeMatched)
break;
}
matchedItems = 0;
}
return result;
}
public class Recipe implements Serializable{
private String instructions;
private String recName;
private String image;
private List<Ingredient> ing = new ArrayList<Ingredient>();
public Recipe(){
}
public Recipe(String item,String quan){
this.ing.add(new Ingredient(item, quan));
}
public List<Ingredient> getIngre(){
return ing;
}
public String getIng(int i){
return ing.get(i).toString();
}
public void setIngredients(List<Ingredient> item){
this.ing = item;
}
public String getRecName() {
return recName;
}
public void setRecName(String recName) {
this.recName = recName;
}
// #Override
public String toString() {
return recName;
}
public String getInstructions() {
return instructions;
}
public void setInstructions(String instructions) {
this.instructions = instructions;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Based on your comments. You could add another variable to your Ingredient class. Like this:
public class Ingredient implements Serializable{
private String name;
private String quantity;
private boolean isImportant;
public Ingredient(){
}
public Ingredient(String name,String quantity){
this.name=name;
this.quantity=quantity;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public boolean getIsImportant() {
return isImportant;
}
public void setIsImportant(boolean isImportant) {
this.isImportant= isImportant;
}
}
Then you could check in the recipe if all the important ingredients are present or not.
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;
}
I have an inventory program written to include an array and a method to calculate total cost for all inventory items entered. I now have to include a subclass that overrides the original to include "one unique feature". I created a new file named ItemDetails to set up for the subclasses of the original Item. I need to include one unique feature and calculate the value of the inventory and calculate a 5% restocking fee in this subclass. Do I just transfer some of the relevant lines into the other class? Or do I write some code twice? I don't know what to do next. Any help is useful. Thanks. This is what I have so far:
package inventory3;
public class ItemDetails extends Items
{
public static void override()
{
private String Name;
private double pNumber, Units, Price;
public ItemDetails()
{
}
}
}
This is the Item class file that it is supposed to override:
package inventory3;
import java.lang.Comparable;
public class Items implements Comparable
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items) item;
return this.getName().compareTo(tmp.getName());
}
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for(int i =0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
}
return combined;
}
}
You simply declare a method with the same signature as the method in the parent class. So yours would look like:
package inventory3;
public class ItemDetails extends Items {
private String Name;
private double pNumber, Units, Price;
public ItemDetails(String Name, double pNumber, double Units, double Price) {
this.Name = Name;
this.pNumber = pNumber;
this.Units = Units;
this.Price = Price;
}
// getters and setters....
// The #Override is optional, but recommended.
#Override
public double calculateTotalPrice() {
return Units * Price * 1.05; // From my understanding this is what you want to do
}
}