Accessing an element inside an Array of an Array - java

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.

Related

Adding to a custom list

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

How to create an Arraylist with an object inside a class in java

The exercise is to have a class named Tenant that will be used to store values of tenants for an apartment. In the main class Prog2 I am trying to create an ArrayList that can hold 4 different values, all regarding the tenant class, which are - the tenant's name, apartment number, initial first payment, and monthly payment. I want to be able to print these values out in separate lines that will provide all 4 pieces of information per tenant - followed by a blank line, and then the same 4 pieces of information for another tenant if there is another one. I can get the program to prompt the questions correctly, but then all I get are nulls and 0's printed out (see below at comment). I appreciate all the help - I'm not the best at this.
// this class is the tenant class that passes all the tenant's
information
public class Tenant {
private String firstName;
private String lastName;
private String aptNumber;
private double yearlyRent;
private String fullName;
private double firstPayment;
private double monthlyPayment;
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
public Tenant() {
}
public void setFirstName(String name) {
firstName = name;
}
public void setLastName(String lName) {
lastName= lName;
}
public void setAptNumber(String apt) {
aptNumber = apt;
}
public void setRent(double rent) {
yearlyRent = rent;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getAptNumber() {
return aptNumber;
}
public double getRent() {
return yearlyRent;
}
public double getFirstPayment() {
double monthlyRent = yearlyRent/12;
firstPayment = monthlyRent * 3;
return firstPayment;
}
public double getmonthlyPayment() {
double firstAndLast = yearlyRent/12;
monthlyPayment = (yearlyRent - firstAndLast)/11;
return monthlyPayment;
}
public String getFullName(){
fullName = firstName + " " + lastName;
return fullName;
}
}
// The below class contains the main method
public class Prog2 {
public static double getDouble(Scanner scan) {
System.out.println("Enter yearly rent:");
while (!scan.hasNextDouble()) {
scan.next();
System.out.println("Error: please enter a numeric
value");
}
return scan.nextDouble();
}
public static void main(String[] args) {
Tenant tnt = new Tenant();
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of tenenats:");
int numTenants = scan.nextInt();
ArrayList<Tenant> list = new ArrayList<Tenant>();
for (int i = 0; i<numTenants; i++) {
System.out.println("Enter first name:");
tnt.setFirstName(scan.next());
System.out.println("Enter last name:");
tnt.setLastName(scan.next());
System.out.println("Enter apt number:");
tnt.setAptNumber(scan.next());
tnt.setRent(getDouble(scan));
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
}
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).getFullName());
System.out.println(list.get(i).getAptNumber());
System.out.println(list.get(i).getFirstPayment());
System.out.println(list.get(i).getmonthlyPayment());
System.out.println();
}
}
}
// this prints out:
null null
null
0.0
0.0
null null
null
0.0
0.0
The issue is with the first constructor in the Tenant class. Remember that the = operator assigns the value of the right operand to the variable in the left operand. In your case the code should look like this:
public Tenant(
String name,
String aptNum,
double fPayment,
double mPayment)
{
fullName = name;
aptNumber = aptNum;
firstPayment = fPayment;
monthlyPayment = mPayment;
}
What I typically do with constructors is name the parameters after the field, then on the left side of the field assignments use this to refer to the field as opposed to the parameter. This ends up looking much clearer:
public Tenant(
String fullName,
String aptNumber,
double firstPayment,
double monthlyPayment)
{
this.fullName = fullname;
this.aptNumber = aptNumber;
this.firstPayment = firstPayment;
this.monthlyPayment = monthlyPayment;
}
this can be tricky to use but this is an example where it can clear things up.
Many things are wrong with your code .
Constructor of
public Tenant(String name, String aptNum, double fPayment, double
mPayment){
name = fullName;
aptNum = aptNumber;
fPayment = firstPayment;
mPayment= monthlyPayment;
}
here your not just assigning null values to your function parameeters, instead of assigning values to your class fields from function parameters.
Also, when you are calling function getFullName() , it will return null as firstName and lastName fields are not initialized.
So, you need to modify your constructor to -
public Tenant(String firstNamename, String lastName, String aptNum, double fPayment, double
mPayment){
this.firstName = firstNamename;
this.lastName = lastName;
this.aptNumber = aptNum;
this.firstPayment = fPayment;
this.monthlyPayment = mPayment;
this.fullName = getFullName();
}
also in for loop , you need to change
list.add(new Tenant(tnt.getFullName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));
to -
list.add(new Tenant(tnt.getFirstName(),tnt.getLastName(), tnt.getAptNumber(),
tnt.getFirstPayment(), tnt.getmonthlyPayment()));

Add new parameters in for using Java ArrayList

I am a beginner using Java and I don't find the solution for this:
public class Company{
private String name;
private int age;
public Company(String n, int a){
name = n;
age = a;
}
/*get and set*/
public static void main(String[] args) {
ArrayList<Company> comp = new ArrayList<Company>();
comp.add(new Company("Tom", 23));
comp.add(new Company("John", 43));
comp.add(new Company("Charles", 25));
}
}
I would like to add parameters in a for, like email, address, etc. But .add is for new elements, no parameters.
Extend the Company class with the email, address fields (1), update the constructor (2), and pass the arguments you want (3).
public class Company {
...
private final String address; // 1
private final String email;
public Company(String n, int a, String address, String email) { // 2
...
this.address = address;
this.email = email;
}
public static void main(String[] args) {
...
comp.add(new Company("Charles", 25, "street", "charles#gmail.com")); // 3
}
}
If you already have an array filled with information for a specific field, you can use a for:
final List<String> emails = Arrays.asList("first#gmail.com", "second#gmail.com");
for (final String email : emails) {
comp.add(new Company(..., ..., ..., email));
}
You need to read about class members.
public class Company{
private String name;
private int age;
private String email;
private String address;
public Company(String n, int a, String e, String addr){
name = n;
age = a;
email = e;
address = addr;
}
First, you need to add variables to your class (that is the place where it will be stored per each class instance, as well as name or age are at the moment
Than you have to modify constructor (or create another one) to be able take these parameters, and also it is good idea to make getters and setters to get or set these parameters individually, so it can looks like this
public class Company{
private String name;
private int age;
private String email;
private String address;
public Company(String n, int a){
name = n;
age = a;
}
public Company(String n, int a,String email, String address){
name = n;
age = a;
this.email = email; //class instance object email is set to email from method parameter
this.address = address;
}
/*get and set*/
public void setEmail(String email){
this.email=email; //explicit setter
}
public String getEmail(){
return this.email;
}
public static void main(String[] args) {
ArrayList<Company> comp = new ArrayList<Company>();
comp.add(new Company("Tom", 23)); //will work, because I let your constructor
comp.add(new Company("John", 43));
comp.add(new Company("Charles", 25));
Company compToAdd= new Company("preparedFoo",22);
compToAdd.setEmail("fooomail"); //will work because setter
comp.add(compToAdd);
comp.add(new Company("FooName", 30,"fooMail","FooAddress")); //will work because new constructor
}
}

How do i store a whole void method in array variable

public void body()
String name = "", address = "",checkin = "", checkout = "";
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
for(k =1;;k++)
{
}
I need to store whole method in a array variable at once.
well actually for every loop i want to create a element in array.
Like chrylis said in his comment you could create a class Reservation with the fields you want to store.
public class Reservation {
private String name;
private String address;
private String checkin;
private String checkout;
public Reservation(String name, String address, String checkin, String checkout) {
this.name = name;
this.address = address;
this.checkin = checkin;
this.checkout = checkout;
}
//getters and setters ...
}
Then you can create a new Object of it in your method and add it to your array
ArrayList<Reservation> reservations = new ArrayList<>();
for(k =1;;k++) {
reservations.add(new Reservation(...));
}
I used an ArrayList instead of an Array because you can add as many elements as you want to an ArrayList

How can I sum values from a getter method within an iterator?

I'm trying to sum numerical values from a getter method (drawing values from an ArrayList) using an iterator.
Function in question:
public void overallTotal()
{
Iterator<Customer> customers = model.getCustomerIterator();
while (customers.hasNext())
{
Customer customer = customers.next();
int sum = 0;
sum = customer.getTotalForAllOrders() + sum;
System.out.println(sum);
}
}
for an interface model.
This is simply printing getTotalForAllOrders() for each customer. I need to (cumulatively) sum them.
Could someone show me how to do this, please?
Customer:
import java.util.ArrayList;
public class Customer
{
private String firstName;
private String lastName;
private String address;
private String phone;
private String email;
private ArrayList<Order> orders;
public Customer(String firstName, String lastName, String address, String phone, String email)
{
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.phone = phone;
this.email = email;
orders = new ArrayList<Order>();
}
public int getTotalForAllOrders()
{
int total = 0;
for (Order order : orders)
{
total += order.getTotal();
}
return total;
}
}
Order:
public class Order
{
private ArrayList<LineItem> lineItems;
public Order()
{
lineItems = new ArrayList<LineItem>();
}
public int getTotal()
{
int total = 0;
for (LineItem item : lineItems)
{
total += item.getSubTotal();
}
return total;
}
}
Iterator:
public Iterator<Customer> getCustomerIterator()
{
return customers.iterator();
}
If I understand your issue correctly, you just need to initialize sum outside of your while loop, you're just redeclaring the variable after the scope breaks.

Categories

Resources