I'm trying to add a booking to a custom booking list.
This is the Booking class
public class Booking {
String forename = null;
String surname = null;
int numberOfSeats = 0;
public Booking() {
this.forename = forename;
this.surname = surname;
this.numberOfSeats = numberOfSeats;
}
In the other class, I have a list declared, have a method to add a booking to this list:
public class TheatreShow {
List<Booking> booking = new ArrayList<Booking>();
public void addBooking(String forename, String surname, int numberOfSeats) {
booking.add(numberOfSeats, surname, numberOfSeats);
}
The error I'm getting is that it's not applicable for the arguments.
The method add(int, Booking) in the type List<Booking> is not applicable for the arguments (int, String, int)
Change
booking.add(numberOfSeats, surname, numberOfSeats);
To
booking.add(new Booking(forename, surname, numberOfSeats));
Your list is a list of Bookings, so it only stores items of type Booking. You need to create a new Boooking with the forename, surname and numberOfSeats you got by parameter before adding to the list.
You have to create all args constructor:
public class Booking {
String forename = null;
String surname = null;
int numberOfSeats = 0;
public Booking(String forename, String surname, int numberOfSeats) {
this.forename = forename;
this.surname = surname;
this.numberOfSeats = numberOfSeats;
}
}
Then you have to create new instance of the Booking and add it to the list:
public class TheatreShow {
List<Booking> booking = new ArrayList<>();
public void addBooking(String forename, String surname, int numberOfSeats){
booking.add(new Booking(forename, surname, numberOfSeats));
}
}
Related
Given the following class:
public class Customer {
protected String firstName;
protected String lastName;
protected String ID;
protected float amountSpent;
// Contructor
// Accessors and mutators
}
public class Gold extends Customer {
protected discount;
// overloaded contructor
// Accessors and mutator
}
and the following code
Customer[][] arr = new Customer[2][1];
Customer[] preferredArr = new Gold[3];
Customer[] regularArr = new Customer[3];
preferredArr[0] = new Gold("John", "Doe", "1234", 45, .12)
regularArr[0] = new Customer("Caroline", "Merritt", "5678", 60)
arr[0] = preferredArr;
arr[1] = regularArr;
How would I access John's information using preferredArr[0].getFirstName() if it is inside of the arr array. Also I can't use ArrayList as specified by my professor. Thanks for the help!
preferredArr[0].getFirstName(), work because the object is in preferredArr. to be exact the reference of the object.
arr[0][0].getFirstName(): also, work, because also, only the reference to the same object is stored in arr[0][0].
class Customer {
protected String firstName;
protected String lastName;
protected String ID;
protected float amountSpent;
// Contructor
Customer(String firstName, String lastName, String ID, float amountSpent)
{
this.firstName = firstName;
this.lastName = lastName;
this.ID = ID;
this.amountSpent = amountSpent;
}
// Accessors and mutators
public String getFirstName()
{
return this.firstName;
}
}
class Gold extends Customer {
protected int discount;
// overloaded contructor
Gold(String firstName, String lastName, String ID, int discount, float amountSpent)
{
super(firstName, lastName, ID, amountSpent);
this.discount = discount;
}
// Accessors and mutator
}
public class Main
{
public static void main(String[] args)
{
Customer[][] arr = new Customer[2][1];
Customer[] preferredArr = new Gold[3];
Customer[] regularArr = new Customer[3];
preferredArr[0] = new Gold("John", "Doe", "1234", 45, 0.12f);
regularArr[0] = new Customer("Caroline", "Merritt", "5678", 60);
arr[0] = preferredArr;
arr[1] = regularArr;
System.out.println("preferredArr[0].getFirstName() = "+preferredArr[0].getFirstName());
System.out.println("arr[0][0].getFirstName() = "+arr[0][0].getFirstName());
}
}
The result :
preferredArr[0].getFirstName() = John
arr[0][0].getFirstName() = John
You can check this : two references to the same object.
And where the object in java are stored
Good Luck.
There are four classes that interact with my project. The aim is to generate an object using enum, using the random values from enum.
The EthicalEngine class. I'll call the method from another class called ScenarioGenerator.
The Person class inherited from the Character abstract class.
I am not sure whether my method of initialization is correct or not. My idea is to initialize the instance of the Person in the ScenarioGenerator class, and use a method getRandomPerson() to call the constructor.
But I stuck, keep getting NullPointerException when I called the method.
Here is part of my Character class:
abstract class Character {
private int age;
private Gender gender;
private BodyType bodyType;
protected Profession profession;
protected AgeCategory ageCategory;
protected boolean isPregnant;
public enum Gender {
MALE, FEMALE, UNKNOWN;
}
public enum BodyType {
AVERAGE, ATHLETIC, OVERWEIGHT, UNSPECIFIED;
}
public enum Profession {
DOCTOR, CEO, CRIMINAL, HOMELESS, UNEMPLOYED, MUSICIAN, BOXER ,UNKNOWN, NONE;
}
public Character(int age, Profession profession, Gender gender, BodyType bodyType, boolean isPregnant) {
this.age = age;
this.profession = profession;
this.gender = gender;
this.bodyType = bodyType;
this.isPregnant = isPregnant;
}
part of my Person class:
Person(int age, Profession profession ,Gender gender, BodyType bodyType, boolean isPregnant) {
super(age, profession, gender, bodyType, isPregnant);
}
public Profession getProfession () { //use getter to generate a random value
//only adults have profession
if (getAge()<=16 || getAge()>68) {
return Profession.NONE;
} else {
return Profession.values()[new Random().nextInt(Profession.values().length)];
}
//other getters and setters
}
Part of my ScenarioGenerator class:
public class ScenarioGenerator {
private Person person;
private Animal animal;
private Scenario scenario;
private Random random = new Random();
private int passengerCountMinimum;
private int passengerCountMaximum;
private int pedestrianCountMininum;
private int pedestrianCountMaximum;
public ScenarioGenerator() {
random.setSeed(random.nextInt());
}
public ScenarioGenerator(long seed) {
this.random = new Random(seed);
}
public Person getRandomPerson() {
//need age, gender, bodyType, profession, pregnancy
Person people = new Person(person.getAge(), person.getProfession(), person.getGender(),person.getBodyType(), person.isPregnant());
return people;
}
Part of my EthicalEngine class:
public class EthicalEngine {
public static void main(String[] args) throws Exception {
EthicalEngine ethicalEngine = new EthicalEngine();
ScenarioGenerator scenarioGenerator = new ScenarioGenerator();
scenarioGenerator.getRandomPerson();
}
you can generate random number and select all values
import java.util.Random;
public class ScenarioGenerator {
public Person getRandomPerson() {
Random rand = new Random();
// max age
int age = rand.nextInt(100);
// no of profession - 1
int profession = rand.nextInt(8);
// no of gender - 1
int gender = rand.nextInt(2);
// no of bodyType - 1
int bodyType = rand.nextInt(3);
int pragnency = rand.nextInt(2);
//need age, gender, bodyType, profession, pregnancy
Person people = new Person(age, Profession.values()[profession], Gender.values()[gender],BodyType.values()[bodyType], pragnency == 1 ? true : false);
return people;
}
}
the psuedo for what im trying to do is
-send Array of EMPLOYEE objects to Restaurant Class
-In Class RESTAURANT give each of the employee objects a name and last name (last name not in employee Class but in PERSON Class which Employee CLass Extends.
-print say employeeList[1].getLastName()
hopefully my code explains better
class Person {
public Person(final String last) {
}
}
class Employee extends Person {
private String firstName;
// getFirstName method
// getLastName Method
Employee(final String first, final String last) {
super(last);
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1]; // my array of Employee objects, all set to null
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
}
}
from main when i try to print System.out.printf("first is %d\n",arrayList.getFirst()); i get null for the value as well as the value for the last name so what is the correct way to go about and set values to objects in the array?
Edit arrayList initialized in Class restaurant by
public Table[] create_table_array(Table table,int number) {
Table[] TableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++) {
TableList[i] = table;
}
return TableList;
Your constructor doesn't save firstName, it should look like:
Employee(String first, String last) {
super(last);
firstName = first;
}
You did not make good constructor of Person class and it class does not have instance variable lastName in which you should assign value you get in constructor as a parameter.
Also constructor of Employee does not assign any value to firstName.
What ArrayList ?As i see you are working with arrays?I didn't see it in code anywhere?
System.out.printf("first is %d\n",**arrayList**.getFirst());so command is wrong.
Any code that has meaning to me and can be compilled is to fix those things and delete formatting options you putted in System.out.printf because you are not formatting numbers.
So code look like :
class Person {
String lastName;
public Person(final String last) {
lastName=last;
}
}
class Employee extends Person {
private String firstName;
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
Employee(final String first, final String last) {
super(last);
firstName=first;
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1];
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
System.out.printf("first is "+employeeList[0].getFirstName()+" "+employeeList[0].getLastName());
}
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Here is what I have so far in my code
public class Person {
public Person()
{
String person = "";
int age = 0;
String city = "";
int sibCount = 0;
// make an instance field for name, city, age, and siblingCount
Person person = new Person();
Person age = new Person();
Person city = new Person();
Person sibCount = new Person();
}
// make a method called parseCommaDelim
public void parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}
}
I am trying return a person instance and I am not sure how to do it. I tried 'return Person;' and my code did not like it.
My toString method is not working either because it does not know what person, age, or city is, and I am not sure why.
What you want to achieve is probably something along the following lines:
public class Person {
// fields
private String person = "";
private int age = 0;
private String city = "";
private int sibCount = 0;
// constructor
public Person() {
}
// public access methods (getters)
public String getPerson() {
return this.person;
}
public int getAge() {
return this.age;
}
public String getCity() {
return this.city;
}
public int getSibCount() {
return this.sibCount;
}
// toString
public String toString() {
return "person: " + person + ", age: " + age + ", city: " + city;
// factory method
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
Person instance = new Person();
instance.person = tokens[0];
instance.age = Integer.parseInt(tokens[1];
instance.city = tokens[2];
// ...
return instance;
}
}
The field person should probably renamed to name. Depending wether you want to make your class immutable or not you may want to add either a constructor which takes all parameters as parameters:
public Person(String name, int age, String city, int sibCount) {
this.name = name;
this.age = age;
this.city = city;
this.sibCount = sibCount;
}
or add setters for the changable fields, for example:
public void setCity(String city) {
this.city = city;
}
btw. with above constructor you could modify the factory to the following slightly cleaner code:
public static Person parseCommaDelim(String s) {
String[] tokens = s.split(",");
String person = tokens[0];
int age = Integer.parseInt(tokens[1];
String city = tokens[2];
int sibCount = Integer.parseInt(tokens[3]);
return new Person(person, age, city, sibCount);
}
public class Person {
public String person;
public int age;
public String city;
public int sibCount;
public Person()
{
person = "";
age = 0;
city = "";
sibCount = 0;
}
// make a method called parseCommaDelim
public String parseCommaDelim(String[] args){
// return a Person instance UNSURE HERE
}
// make a toString method
public String toString()
{
String str = "person" + person + "age" + age + "city" + city;
return str;
}
}
The problem is that I need to create new incremental ID for each new customer and add it to the Set, I'm trying to do it with the while loop, but it seems not to be right
public class Bank {
private String name;
private Set<Customer> customers = new HashSet<Customer>();
private Set<AbstractAccount> accounts = new HashSet<AbstractAccount>();
private Integer lastCustomerId = 0;
private Integer lastAccountId = 0;
public Integer addCustomer(String firstName, String lastName) {
// generate id from lastCustomerId and increment it
// add to Set
return lastCustomerId++;
}
public Integer addAccount(Integer ownerId, AccountType type) {
// add to Set
}
}
Im not sure if is that what you want...
public class Bank
{
private String name;
private Set<Customer> customers = new HashSet<Customer>();
private Set<AbstractAccount> accounts = new HashSet<AbstractAccount>();
private static int lastCustomerId = 0;
private static int lastAccountId = 0;
public static int GetNextCustomerID()
{
lastCustomerId++;
return lastCustomerId;
}
public static int GetNextAccountID()
{
lastAccountId++;
return lastAccountId;
}
public int addCustomer(String firstName, String lastName)
{
// generate id from lastCustomerId and increment it
int customerId = GetNextCustomerID();
// add to Set
}
public int addAccount(int ownerId, AccountType type)
{
// add to Set
int accountId = GetNextAccountID();
}
}