Java object scope between methods - java

I'm having issues with this code running, I'm trying to get the program to print the strings below by using input from the other classes. As you can see, the info put into the new Bride and Location objects are being put in to a Wedding Object and then I need to try and retrieve the details from the wedding object and display it on screen like so:
Wedding data:
Bride: Amy Cronos, age: 29
Location: South Rd, suburb: Tonsley
but I am instead met with 4 identical errors relating to the place.getName, place.getSuburb() etc. etc. that say
Main.java:6: error: cannot find symbol
System.out.println("Location"+place.getStreet()+", suburb:
"+place.getsuburb());
symbol: variable place
location: class Main
I'm pretty sure this has something to do with the scope, but cant work out what I need to do.
What is causing this error and how do I fix it?
Here is the code:
public class WeddingDetails {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person, place);
show(wed);
}
public static void show(Wedding wed) {
System.out.println("Wedding data:");
System.out.println("Bride: " + person.getName() + ", age: " + person.getAge());
System.out.println("Location: " + place.getStreet() + ", suburb: " + place.getSuburb());
}
public static class Location {
private String suburb;
private String street;
Location(String suburb, String street) {
this.suburb = suburb;
this.street = street;
}
public String getSuburb() {
return suburb;
}
public String getStreet() {
return street;
}
}
public static class Bride {
private String name;
private int age;
Bride(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place) {
this.person = person;
this.place = place;
}
public Bride getBride() {
return person;
}
public Location getPlace() {
return place;
}
}
}

The issue here is your println statements are trying to access methods within objects, but by calling those methods on the wrong object. You should be accessing the Bride and Location objects with the Wedding class' getters (getBride() and getPlace(). The complete call would be wed.getBride().getName() and wed.getPlace().getStreet() so on.
Corrected code is below. NOTE: for the purposes of being able to compile all of the code inside one class, I added the static keyword to the Bride, Location and Wedding class declarations. You can just remove the static and copy and paste each class back into your .java files.
public class WeddingDetails {
public static void main(String[] args) {
Bride person = new Bride("Amy Cronos", 29);
Location place = new Location("Tonsley", "South Rd");
Wedding wed = new Wedding(person, place);
show(wed);
}
public static void show(Wedding wed) {
System.out.println("Wedding data:");
System.out.println("Bride: " + wed.getBride().getName() + ", age: " + wed.getBride().getAge());
System.out.println("Location: " + wed.getPlace().getStreet() + ", suburb: " + wed.getPlace().getSuburb());
}
public static class Location {
private String suburb;
private String street;
Location(String suburb, String street) {
this.suburb = suburb;
this.street = street;
}
public String getSuburb() {
return suburb;
}
public String getStreet() {
return street;
}
}
public static class Bride {
private String name;
private int age;
Bride(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static class Wedding {
private Bride person;
private Location place;
Wedding(Bride person, Location place) {
this.person = person;
this.place = place;
}
public Bride getBride() {
return person;
}
public Location getPlace() {
return place;
}
}
}

Related

Problem writing a builder for a class in java

I have problem writing a builder for a class in java. It always gives me an error saying could not find symbol.
class Company {
private String name;
private String address;
private String contact;
private int sizeOfEmployee;
private Date createdTime;
#Override
public String toString() {
return "Company{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
", contact='" + contact + '\'' +
", sizeOfEmployee=" + sizeOfEmployee +
", createdTime=" + createdTime +
'}';
}
public static class builder {
private String name;
private String address;
private String contact;
private int sizeOfEmployee;
private Date createdTime;
public builder Name (String name){
this.name = name;
return this;
}
public builder address(String address){
this.address = address;
return this;
}
public builder contact(String contact){
this.contact = contact;
return this;
}
public builder size(int sizeOfEmployee){
this.sizeOfEmployee = sizeOfEmployee;
return this;
}
public builder date(Date createdTime){
this.createdTime = createdTime;
return this;
}
}
}
I would like to write a builder that could print out my Company class. Could anyone tell me why my builder is not working? I search for how to write a builder and try to copy the method. But it's not working here. It gives me an error saying error can not find symbol.
If I call
Company abc = Company.builder().name("abc").address("Virginia").createdTime(new Date()).sizeOfEmployee(300).contact("12345").build();
It will print out
Company{name='abc', address='Virginia', contact='12345', sizeOfEmployee=300, createdTime=Wed Oct 21 11:50:41 EDT 2020}
You are calling static method builder 'Company.builder()' which does not exists.
You can solve the problem this way:
public class Company {
private String name;
private String address;
public static CompanyBuilder builder() {
return new CompanyBuilder();
}
private static class CompanyBuilder {
private final Company company = new Company();
public CompanyBuilder name(String name){
company.name = name;
return this;
}
public CompanyBuilder address(String address){
company.address = address;
return this;
}
public Company build() {
return company;
}
}
public static void main(String[] args) {
System.out.println(Company.builder().name("name").address("address").build());
}
}
I would suggest Lombok for java projects. With one annotation #Builder including the Lombok plugin and dependency you can solve the problem, also you can use a lot of features instead of boilerplate code.
import lombok.Builder;
import lombok.ToString;
#Builder
#ToString
public class Company {
private String name;
private String address;
public static void main(String[] args) {
System.out.println(Company.builder().name("name").address("address").build());
}
}

Class with an ArrayList inside

I'm new to programming and i'd like some help.
I want to make a class that can add name,age and multiple phone numbers ( in some cases it will be 1, in others 4, etc...) and then show all the info.
I don't want to make it by creating another class for the ArrayList,
I'd like to do it all inside this class, I guess it's something simple to do but I can't figure this out and I'm not finding the solution I want.
what can I do about it? thx in advance, first time posting If I did something wrong please tell me.
import java.util.ArrayList;
public class Athlete
{
private String name;
private int age;
private ArrayList<String> phones = new ArrayList();
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
}
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;
}
public ArrayList<String> getPhones()
{
return phones;
}
public void setPhones(ArrayList<String> phones)
{
this.phones = phones;
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phones + '}';
}
}
You could make an inner class for PhoneList and use that type instead of directly working with the ArrayList.
public class Athlete
{
private String name;
private int age;
private PhoneList phoneList;
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
phoneList = new PhoneList();
}
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;
}
// Maybe just return the toString (or a read only list)
public PhoneList getPhones()
{
return phoneList;
}
publicvoid addPhone(String phone)
{
phoneList.add(phone);
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phoneList + '}';
}
private class PhoneList
{
private ArrayList<String> list = new ArrayList<String>();
private void add(String phone)
{
list.add(phone);
}
#Override
public String toString()
{
StringBuffer b = new StringBuffer(32);
for (String ph : list)
{
b.append(ph + "\n"); // Or something
}
return b.toString();
}
}
}

Java - How can I create an array of a different class and iterate through it calling its toString method?

I have a Person class with the fields "name" and "phoneNumber" that are set through the constructor. I am trying to create a separate testing class that will create an array of Person and iterate through them by calling to their toString() method.
I am not sure how to do this, any help is appreciated.
Here is my first class which is all I have so far;
public class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Hope this will help,
public class Test {
public static void main(String[] args) {
Person array[] = {new Person("Jason", "123456"), new Person("Karl", "78945"), new Person("Tom", "789456")};
for(int i = 0; i < array.length; i++){
array[i].toString();
//System.out.println(array[i].toString());
}
}
}
class Person
{
private String name;
private String phoneNumber;
public Person(String name, String phoneNumber)
{
this.name = name;
this.phoneNumber = phoneNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return phoneNumber;
}
public String getPerson()
{
return name + " " + phoneNumber;
}
#Override
public String toString()
{
return "["+getPerson()+"]";
}
}
Save the file as Test.java
Firstly the toString method is for an INDIVIDUAL Person object, and cannot be applied to a whole set, you need to make the method static and have a whole static array defined in the class to be able to go through all instances of the Person class.
private static Person[] pArray = new Person[20];
//I picked 20 randomly, if you want any possible number use an arrayList<Person>
private static int count = 0;
In the constructor
pArray[count] = this;
count++;
Then your toString method:
String list = "[";
for(Person p : this.pArray)
list = list + p.getPerson() + " ,"
list = list + "]";
return list;

Null values when printing out arrayList?

Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)

Creating an object and calling it

this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)

Categories

Resources