I've to implement Ticket class in java.
This is my code:
public class Ticket {
private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;
public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public ArrayList<Ticket> getAllTickets() {
return ticketList;
}
And my main problem is that how to do that creating an instance of Ticket class, ticketList has the newly created Ticket object. Because later I've to use public getAllTickets() method to get all tickets.
Thanks in advance!
Complete example:
package stackoverflow;
import java.math.BigDecimal;
public class Ticket {
private String name;
private BigDecimal defaultPrice;
public Ticket(String name, BigDecimal defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name =
name;
}
public BigDecimal getDefaultPrice() {
return defaultPrice;
}
public void setDefaultPrice(BigDecimal defaultPrice) {
this.defaultPrice = defaultPrice;
}
}
Event class:
package stackoverflow;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Event {
private Date date;
private List<Ticket> ticketList;
public Event(Date date) {
this.date = date;
this.ticketList = new ArrayList<>();
}
public void addTicket(Ticket ticket) {
this.ticketList.add(ticket);
}
public List<Ticket> getTicketList() {
return this.ticketList;
}
}
Main class:
package stackoverflow;
import java.math.BigDecimal;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Event eventX = new Event(new Date());
eventX.addTicket(new Ticket("ticket1", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket2", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticket3", new BigDecimal(50)));
eventX.addTicket(new Ticket("ticketPremium", new BigDecimal(100)));
for (Ticket ticket: eventX.getTicketList()) {
System.out.println("name:" + ticket.getName() + " price: " + ticket.getDefaultPrice());
}
}
}
I can't comment so I will have to just answer.
Do you mean that you need each ticket to be stored in the list whenever one is created?
If so make the constructor private and provide a factory method.
Like so:
public class Ticket {
private String name;
private Float defaultPrice;
private Event event;
private static ArrayList<Ticket> ticketList;
static {
ticketList = new ArrayList<>();
}
private Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
}
public static ArrayList<Ticket> getAllTickets() {
return ticketList;
}`
public static Ticket getInstance(String name, Float defaultPrice)
{
Ticket temp = new Ticket(name, defaultPrice);
ticketList.add(temp);
return temp;
}
Option 1
If you are trying to make sure every new ticket adds itself to its own list of tickets, this can easily be taken care of in the constructor:
public Ticket(String name, Float defaultPrice) {
this.name = name;
this.defaultPrice = defaultPrice;
this.ticketList = new ArrayList<Ticket>();
this.ticketList.add(this);
}
Option 2
You could also have a separate class method to add tickets to the list, and instead use that when you initialize a new ticket. For example your Ticket class would have the following:
public void addTicketToList(Ticket ticket){
this.ticketList.add(ticket);
}
Then, when you create a new ticket you can use this:
Ticket newTicket = new Ticket();
newTicket.addTicketToList(newTicket);
Related
The point is to create an abstraction that makes class1 and class2 look the same, not to create an adaptor that makes, for instance, class1 look like class2. I don’t want the BankController to ever directly use any classes in the com.bank1 and com.bank2 packages.I would like not to edit bank1 and bank2 class everything should get done in bankcontroller.java. The skeleton code is below.
Bankcontroller.java:
package com.pyyne.challenge.bank;
public class BankController {
}
public void printBalances() {
System.out.println("Implement me to pull balance information from all available bank integrations and display them, one after the other.");
}
public void printTransactions() {
System.out.println("Implement me to pull transactions from all available bank integrations and display them, one after the other.");
}
}
Bank1AccountSource.java:
package com.bank1.integration;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class Bank1AccountSource {
public Double getAccountBalance(long accountId) {
return 215.5d;
}
public String getAccountCurrency(long accountId) {
return "USD";
}
public List<Bank1Transaction> getTransactions(long accountId, Date fromDate, Date toDate) {
return Arrays.asList(
new Bank1Transaction(100d, Bank1Transaction.TYPE_CREDIT, "Check deposit"),
new Bank1Transaction(25.5d, Bank1Transaction.TYPE_DEBIT, "Debit card purchase"),
new Bank1Transaction(225d, Bank1Transaction.TYPE_DEBIT, "Rent payment")
);
}
}
Bank2AccountSource.java:
package com.bank2.integration;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
public class Bank2AccountSource {
public Bank2AccountBalance getBalance(long accountNum) {
return new Bank2AccountBalance(512.5d, "USD");
}
public List<Bank2AccountTransaction> getTransactions(long accountNum, Date fromDate, Date toDate) {
return Arrays.asList(
new Bank2AccountTransaction(125d, Bank2AccountTransaction.TRANSACTION_TYPES.DEBIT, "Amazon.com"),
new Bank2AccountTransaction(500d, Bank2AccountTransaction.TRANSACTION_TYPES.DEBIT, "Car insurance"),
new Bank2AccountTransaction(800d, Bank2AccountTransaction.TRANSACTION_TYPES.CREDIT, "Salary")
);
}
}
Bank1Transaction.java:
package com.bank1.integration;
import java.util.Date;
public class Bank1Transaction {
public static int TYPE_CREDIT = 1;
public static int TYPE_DEBIT = 2;
private double amount;
private int type;
private String text;
public Bank1Transaction(double amount, int type, String text) {
this.amount = amount;
this.type = type;
this.text = text;
}
public double getAmount() {
return amount;
}
public int getType() {
return type;
}
public String getText() {
return text;
}
}
Bank2Transaction.java:
package com.bank2.integration;
public class Bank2AccountTransaction {
public static enum TRANSACTION_TYPES {
DEBIT, CREDIT
}
private double amount;
private TRANSACTION_TYPES type;
private String text;
public Bank2AccountTransaction(double amount, TRANSACTION_TYPES type, String text) {
this.amount = amount;
this.type = type;
this.text = text;
}
public double getAmount() {
return amount;
}
public TRANSACTION_TYPES getType() {
return type;
}
public String getText() {
return text;
}
}
Bank2AccountBalance:
package com.bank2.integration;
public class Bank2AccountBalance {
private double balance;
private String currency;
public Bank2AccountBalance(double balance, String currency) {
this.balance = balance;
this.currency = currency;
}
public double getBalance() {
return balance;
}
public String getCurrency() {
return currency;
}
}
So I have 4 classes, Testest which has a main method, Phone which extends Product, Product and ProductDB which has a hashmap. When I make a new phone I want the phone to be stored in the database automatically.
public class Product {
protected String productID;
protected String name;
private String description;
private double price;
public Product(){
Product db = new ProductDB();
productID = this.toString();
db.add(productID, this);
}
(Getter and setter methods here...)
}
public class Phone extends Product {
private String make;
private String model;
private int storage;
public Phone(String make, String model, int storage){
this.make = make;
this.model = model;
this.storage = storage;
}
(Getter and setter methods here...)
}
import java.util.HashMap;
public class ProductDB {
private HashMap<String,Product> products = new HashMap<String, Product>();
public void add(String productID, Product product){
products.put(productID, product);
}
public void remove(String productID){
products.remove(productID);
}
public Product find(String productID){
return products.get(productID);
}
public Object showAll(){
return products.values().toArray();
}
}
public class Testest{
public static void main(String[] args){
ProductDB db = new ProductDB();
Phone phone1 = new Phone("Huwawei P30", "HP30", 50000);
Phone phone2 = new Phone("Huwawei P30 Pro", "HP30PRO", 70000);
Phone phone3 = new Phone("Samsung Galaxy SX", "SGSX", 65000);
System.out.println(db.find(phone1.productID));
System.out.println(phone1.productID);
}
}
I want this to return the object when I look for that specific id, but the problem is that the HashMap is empty for some reason
Edit I made productID private. Still nothing
It seems you want your database to include all created phones, in this case instead of creating a database each time which will be useless and also because your database is accessed from several places it will be more consistent to make your database fields and methods static and just access it from where you want:
public class ProductDB {
final private static HashMap<String,Product> products = new HashMap<String, Product>();
public static void add(String productID, Product product){
products.put(productID, product);
}
public static void remove(String productID){
products.remove(productID);
}
public static Product find(String productID){
return products.get(productID);
}
public static Object showAll(){
return products.values().toArray();
}
}
And then in Product constructor just write:
public Product{
productID = this.toString();
ProductDB.add(productID, this);
}
I am new to java and reporting tool BIRT, I am trying to create a simple report using Pojo in Birt but I can't get it to work I create my java classes in other project and generate a jar file after that I use it to create a data source but when I try to create a data set it doesnt work, I couldn't select classes to proceed
package com.test.pojoproject;
import java.io.Serializable;
public class Person implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int id;
private String name;
private String address;
public Person(){
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.test.pojoproject;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class Main implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static List<Person> list = new ArrayList<Person>();
public static void main(String[] args) {
Main.generateData();
Main.getList();
// display created list
//list.forEach(person -> System.out.println(person.getName()));
}
public static void generateData(){
List<Person> list = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
list.add(person);
}
Main.list = list;
}
public static List<Person> getList(){
return Main.list;
}
}
I found a solution BIRT needs to use a class withe methodes open, next and close I will post my dataset class below
package com.test.pojoproject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class PersonDataSet {
public Iterator<Person> itr;
public List<Person> getPersons() {
List<Person> persons = new ArrayList<Person>();
for (int i = 0; i < 30; i++) {
Person person = new Person();
person.setId(i+1);
person.setName("person " + (i+1));
person.setAddress("address " + (i+1));
persons.add(person);
}
return persons;
}
public void open(Object obj, Map<String,Object> map) {
}
public Object next() {
if (itr == null)
itr = getPersons().iterator();
if (itr.hasNext())
return itr.next();
return null;
}
public void close() {
}
}
I have two packages lets give them the name package 1 and package 2.
Class A and Class B is in package1. Class A contains an ArrayList called PTable. Class B contains a function called query() that filters through PTable,in Class A, based on a certain conditions and returns an ArrayList called result that contains all the elements from PTable that meet that condition.
I now have package2 that contains Class C. Class C imports Class B from package 1; Class C is a subclass of HttpServlet. I create an object of Class B in class C and initializer it.
I then call the function query() and assign it to a variable called results. When I try and get the properties of an element at a certain index, I can't see the properties of the original objects stored in the ArrayList PTable.[This is what appears when I try and access the properties of the objects. My aim is to see the second image ][1]
Nice to ask questions but first spend sometime studying Java. Read a book or online and you will learn about casting very quickly. Also about classes, super classes etc
Your storing the objects in a variable of type Element (your results array list).
Cast the object back to the type it belongs too and then you will see the variables.
Code design note : storing different types of classesin the same array list is legal and possible but bug prone. Try to avoid it. If you change the order of storing variables into the list, you need to change all the access code too. Anyway happy learning.
There are free online Java tutorials study them -> https://www.google.co.in/search?q=java+tutorial+beginner
Sample class, in the main method try to get the object at position 1 and cast it to a Person :
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Car {
private String manufacturer;
private String model;
private double price;
private int yearOfMfr;
private Date dateBought;
private String licenceNumber;
public Car() {
super();
}
public Car(String manufacturer, String model, double price, int yearOfMfr, Date dateBought, String licenceNumber) {
super();
this.manufacturer = manufacturer;
this.model = model;
this.price = price;
this.yearOfMfr = yearOfMfr;
this.dateBought = dateBought;
this.licenceNumber = licenceNumber;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getYearOfMfr() {
return yearOfMfr;
}
public void setYearOfMfr(int yearOfMfr) {
this.yearOfMfr = yearOfMfr;
}
public Date getDateBought() {
return dateBought;
}
public void setDateBought(Date dateBought) {
this.dateBought = dateBought;
}
public String getLicenceNumber() {
return licenceNumber;
}
public void setLicenceNumber(String licenceNumber) {
this.licenceNumber = licenceNumber;
}
}
public class DemoApp {
public static void main(String[] args) {
List<Object> results = new ArrayList<>();
DemoApp app = new DemoApp();
app.fillItUp(results);
Car acar = (Car) results.get(0);
acar.setLicenceNumber("Flying Duck");
}
private void fillItUp(List<Object> results) {
Car car = new Car("sel2in", "electric_VTOL", 540923, 2018, new Date(2018, 3, 32), "Skyprog");
results.add(car);
results.add(new Person("tushar", 39));
}
}
I have two classes: profesor and subject
public class Profesor {
private int numbClassroom;
public Profesor(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String ToString(){
return "Number of classroom: "+numbClassroom;
} }
The second class is:
public class Subject{
String name;
Profesor lecturer = new Profesor();
Date yearOfStudy;
public void Dodeli(Profesor p){
??????
}}
I do not know how to add professor like a lecturer to a current subject
Like this? I don't see any problem.
public void Dodeli(Profesor p){
lecturer = p;
}
Profesor lecturer = new Profesor();
No need to instantiate lecturer. Just declare it. Then have getter/setter methods for it
Then you can assign Professor to Subject
Subject subj = new Subject("OOP"); //assuming you have corresponding constructor
subj.setLecturer(new Professor()); //or if you have existing prof object
Maybe require something like this : try to encapsulate your code
public class Professor {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Subject{
private String name;
private Professor professor;
private int numbClassroom;
private Date yearOfStudy;
public int getNumbClassroom() {
return numbClassroom;
}
public void setNumbClassroom(int numbClassroom) {
this.numbClassroom = numbClassroom;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Professor getProfesor() {
return professor;
}
public void setProfesor(Professor profesor) {
this.professor = profesor;
}
public void Dodeli(){
System.out.println("Pofessor "+getProfesor().getName()+" is teaching "+getName()+" in Room NO :"+getNumbClassroom());
}
}
public class TestImpl {
public static void main(String arr[])
{
Subject subject = new Subject();
Professor professor = new Professor();
subject.setName("Biology");
professor.setName("MR.X");
subject.setNumbClassroom(1111);
subject.setProfesor(professor);
subject.Dodeli();
}
}