I'm just going through inner classes but I'm getting the wrong output.
I'm basically trying to create a student object with two different addresses using an address class but I'm getting some ridiculous output. I'm clearly doing something completely wrong so if anyone could help that would be brilliant.
Student class:
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet, int uniNumber, String uniStreet) {
this.name = name;
homeAddress = new Address(houseNumber, homeStreet);
uniAddress = new Address(uniNumber, uniStreet);
}
public void setUniAddress (Address uniAddress){
this.uniAddress = uniAddress;
}
public class Address {
public int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
}
public String toString() {
String a = name + "\n" + homeAddress + " " + uniAddress;
return a;
}
}
and my test student class to create the object and to run the toString:
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student("Cathy", 21, "Smithfield Drive", 72, "Nottingham Drive");
Student.Address anotherAddress
= s1.new Address(8, "Deerfield Way");
System.out.println(s1.toString());
}
the output i'm getting is: Cathy
student.Student$Address#2760e8a2 student.Student$Address#4b48f7e0
Thanks
If you want nice output instead of something like Cathy student.Student$Address#2760e8a2, then you need to override the toString() method in your class Address.
Currently, the toString() method that you have is in class Student, not in class Address - carefully check the { and }.
You need to implement the toString()-Method of Adress as well.
public class Address {
public int number;
private String street;
public Address(int no, String street) {
number = no;
this.street = street;
}
public String toString() {
return street + Integer.valueOf(number);
}
Related
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;
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;
}
}
}
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)
I have an past exam question that says:
"Create a class Element that records the name of the element as a String and has a public method, toString that returns the String name. Define a constructor for the class (that should receive a String to initialise the name)."
I gave it a go and don't where to go from here...
main class is:
public class builder {
public static void main(String[] args) {
element builderObject = new element(elementName);
}
}
and constructor is:
import java.util.*;
class element {
public int getInt(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first number");
String elementName = scan.nextLine();
System.out.println("%s");
}
public String toString() {
return elementName;
}
}
Don't get frustrated. Please read java tutorials first and understand the concepts. your exam question is very clear on what you need to do. Atleast for this question, you need to know what is constructor, the purpose of having toString() in a class.
May be the below can help you.
public class Element {
private String elementName;
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
I can't think of a way to explain this without actually giving the answer, so....
public class Element { /// Create class Element
private final String name; // Record the 'name'
public Element(String name) { // constructor receives and sets the name
this.name = name;
}
public String toString() { // public method toString() returns the name
return name;
}
}
You are missing the constructor itself. The point of constructors is to initialize the object, usually by saving the given parameters to data members.
E.g.:
class Element {
/** A data member to save the Element's name */
private String elementName;
/** A constructor from an Element's name*/
public Element(String elementName) {
this.elementName = elementName;
}
#Override
public String toString() {
return elementName;
}
}
class Element {
private String name = "";
/**
/* Constructor
/**/
public void Element(final String name){
this.name = name;
}
#Override
public String toString(){
return name;
}
}
You don't have a constructor in there. A constructor typically looks something like this:
public class MyClass {
private String name;
private int age;
//This here is the constructor:
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
//here's a toString method just for demonstration
#Override
public String toString() {
return "Hello, my name is " + name + " and I am " + age + " years old!";
}
}
You should be able to use that as a guideline for making your own constructor.
class Element
{
private String name = "UNSET";
public String getName() { return name; }
public Element(String name) {
this.name = name;
}
public String toString() {
return getName();
}
}
You are missing a constructor you might be looking for something like this
public class Element{
private String name;
public Element(String name){ //Constructor is a method, having same name as class
this.name = name;
}
public String toString(){
return name;
}
}
A note
I take you are starting with java, In java class names usually start with capital letter, thus element should be Element. Its important that one picks up good habits early..
I have created a (Person,Student,Employee,Faculty and Staff)classes. Person has to subclasses Student and Employee.
Employee has two subclasses Faculty and Staff. I have done all the codings an they are working fine except my driver class TestPerson program its giving compilation errors
Note: A test program that Creates a Person,Student,Employee,Faculty,Staff, and invokes their toString Method.
The errors of driver class TestPerson.java are below:-
error: constructor Student in class Student cannot be applied to given types;
error: no suitable constructor found for Employee(String,String,String,String)
error: constructor Faculty in class Faculty cannot be applied to given types;
error: no suitable constructor found for Staff(String,String,String,String)"
**I am just providing the codes of the driver class. If you need my other codings of the other classes, please state in the comment, and I will immediately post it.
Please see my codings below:-
public class TestPerson {
public static void main(String[] args) {
Person person = new Person("John Doe", "123 Somewhere", "415-555-1212", "johndoe#somewhere.com");
Person student = new Student("Mary Jane", "555 School Street", "650-555-1212", "mj#abc.com", "junior");
Person employee = new Employee("Tom Jones", "777 B Street", "40-88-889-999", "tj#xyz.com");
Person faculty = new Faculty("Jill Johnson", "999 Park Ave", "92-52-22-3-333", "jj#abcxyz.com");
Person staff = new Staff("Jack Box", "21 Jump Street", "707-21-2112", "jib#jack.com");
System.out.println(person.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
System.out.println(faculty.toString() + "\n");
System.out.println(staff.toString() + "\n");
}
}
//Person Class
public class Person {
private String name;
private String address;
private String phone_number;
private String email_address;
public Person() {
}
public Person(String newName, String newAddress, String newPhone_number, String newEmail){
name = newName;
address = newAddress;
phone_number = newPhone_number;
email_address = newEmail;
}
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public void setAddress(String newAddress){
address = newAddress;
}
public String getAddress(){
return address;
}
public void setPhone(String newPhone_number){
phone_number = newPhone_number;
}
public String getPhone(){
return phone_number;
}
public void setEmail(String newEmail){
email_address = newEmail;
}
public String getEmail(){
return email_address;
}
public String toString(){
return "Name :"+getName();
}
}
//Student class
public class Student extends Person {
public final String class_status;
public Student(String name, String address, int phone, String email, String classStatus) {
super(name, address, phone, email);
class_status = classStatus;
}
public String toString(){
return "Student Status: " + super.getName();
}
}
//Employee Class
import java.util.Date;
public class Employee extends Person{
private String office;
private double salary;
private Date hire;
public Employee() {
}
public Employee(String name, String address, int phone, String email){
super(name, address, phone, email);
}
public Employee(String office, double salary, Date hire){
this.office = office;
this.salary = salary;
this.hire = hire;
}
public void setOffice(String office){
this.office = office;
}
public String getOffice(){
return this.office;
}
public void setSalary(double salary){
this.salary = salary;
}
public double getSalary(){
return this.salary;
}
public void setHire(Date hire){
this.hire = hire;
}
public Date getHire(){
return this.hire;
}
public String toString(){
return "Office " + super.getName();
}
}
//Faculty Class
public class Faculty extends Employee {
private String officeHours;
private int rank;
public Faculty(String name, String address, int phone, String email) {
super(name, address, phone, email);
}
public String toString(){
return "Office " + super.getOffice();
}
}
//Staff Class
public class Staff extends Employee {
private String title;
public Staff(String name, String address, int phone, String email) {
super(name, address, phone, email);
}
public Staff(String title){
this.title = title;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public String toString(){
return "Title :" + super.getName();
}
}
The reason you are getting those errors is that the constructors don't exist.
error: constructor Student in class Student cannot be applied to given
types; error: no suitable constructor found for
Employee(String,String,String,String)
That means you will not get the code to compile until you have this:
Student(String name, String addr, String phone, String email) {
....
}
Assuming you have set the properties in the constructor, toString would look like this:
public String toString() {
return this.name + "\n" + this.addr + "\n" + this.phone + "\n" + this.email;
}
UPDATE
Your problem is that Student has only this constructor:
public Student(String name, String address, int phone, String email, String classStatus)
Student needs a constructor which takes only four strings as its parameters. Alternatively, you can make everything take the five parameters you specified.
It's perhaps not related to the question itself, but I think the design could be refined like this:
define abstract class Role with the name of role
define classes Student, Employee, Staff whatever inheriting Role
define class Person with common properties for all person type, names etc, and having property of type Role inside
then define toString on Person and in all Role implementation
in this way you will be able to extend or modify Persons independently from Roles, which makes the design more flexible
The constructor of Person requires a String as third argument, but you are trying to pass int phone to the super-constructor in your sub-classes. That won't work because it's the wrong type.
By the way: you should always represent phone numbers with strings, not with integers.
It doesn't make sense to add or subtract phone numbers.
Integers don't allow leading zeros, which are used for area codes in some
countries.
Integers can't be larger than 2147483648. When you
try to store very long telephone numbers, this seemingly arbitrary
limit will cause very unexpected bugs.
First Set the Phone Number datatype as integer in all the classes ..
main Function will be:
public class TestPerson {
public static void main(String[] args) {
Person person = new Person("John Doe", "123 Somewhere", "415-555-1212",
"johndoe#somewhere.com");
Person student = new Student("Mary Jane", "555 School Street",
650-555-1212, "mj#abc.com", "junior");
Person employee = new Employee("Tom Jones", "777 B Street",
40-88-889-999, "tj#xyz.com");
Person faculty = new Faculty("Jill Johnson", "999 Park Ave",
92-52-22-3-333, "jj#abcxyz.com");
Person staff = new Staff("Jack Box", "21 Jump Street", 707-21-2112,
"jib#jack.com");
System.out.println(person.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
System.out.println(faculty.toString() + "\n");
System.out.println(staff.toString() + "\n");
}
}