Based on one of the Head First books examples I'm having a little trouble in which the toString method is causing issues with my student and they're uni and home address being outputted correctly. All i'm trying to do is output if a students uni address is empty use his home address else use the uni one.
But my test data looks like the following
John John72 Nottingham Drive
John72 Nottingham Drive
public class Test {
public static void main(String[] args){
Student student1 = new Student("John", 19, "Walkers Way");
student1.setUniAddress(72, "Nottingham Drive");
System.out.print(student1.toString());
}
}
Other Class
public class Student {
private String name;
private Address homeAddress, uniAddress;
public Student(String name, int houseNumber, String homeStreet){
this.name = name;
this.homeAddress = new Address(houseNumber, homeStreet);
}
public String getName() { return this.name; }
public Address getHomeAddress(){
if(this.uniAddress == null){
return this.homeAddress;
}else{
return getUniAddress();//this.uniAddress;
}
}
public Address getUniAddress() { return this.uniAddress; }
public void setUniAddress(int number, String add){
Address address = new Address(number, add);
uniAddress = address;
}
#Override
public String toString(){
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
}
public class Address{
private int number;
private String street;
public Address(int no, String street){
this.number = no;
this.street = street;
}
#Override
public String toString(){
return name + number + " " + street + "\n";
}
}
}
Your getHomeAddress method takes care of displaying the uni address, so this line:
return getName() + " " + getHomeAddress() + " " + getUniAddress() + "\n";
can be shortened to:
return getName() + " " + getHomeAddress() + " " + "\n";
Otherwise your getHomeAddress method will pull the uni address, then your getUniAddress method will pull the uni address again.
Also in your address toString you are pulling the person's name and you probably didn't mean to (and you might not want a newline here either since you have a newline in your other toString method).
#Override
public String toString(){
return number + " " + street;
}
Related
I'm trying to override the toString() method and print without the hash. When I use my tostring() method when trying to print it requires me to create another object like asset server = new asset();. When I do this and use just server it returns the default constructor or it gives an error when I use server[i]. The code I have written returns this:
`ant -f C:\\Users\\kalle\\Documents\\NetBeansProjects\\assign7 -
Dnb.internal.action.name=run run
init:
Deleting: C:\Users\kalle\Documents\NetBeansProjects\assign7\build\built-
jar.properties
deps-jar:
Updating property file:
C:\Users\kalle\Documents\NetBeansProjects\assign7\build\built-
jar.properties
compile:
run:
server switch etc.
0
vendor model number
serial number
1
driver.asset#15db9742
server
server0
10
a1
1
driver.asset#15db9742
server
server1
20
a2
1
BUILD SUCCESSFUL (total time: 0 seconds)`
Here is my code:`
package driver;
public class Driver {
public static void main(String[] args) {
int i;
asset basic = new asset();
asset[] server = new asset[2];
server[0]= new asset("server", 10, "server0", "a1", 1);
server[1]= new asset("server", 20, "server1", "a2",1);
for (i=0;i<server.length;i++){
System.out.println(basic);
System.out.println(server[i].Type);
System.out.println(server[i].Name);
System.out.println(server[i].ID);
System.out.println(server[i].Serial);
System.out.println(server[i].PID);
}
}
}
public class asset {
String Type;
int ID;
String Name;
String Serial;
int PID;
int i;
public String getType(){
return Type;
}
public void setType(String Type){
this.Type = Type;
}
public int getID(){
return ID;
}
public void setID(int getid){
Integer.toString(ID);
this.ID= ID;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public String getSerial(){
return Serial;
}
public void setSerial(String Serial){
this.Serial = Serial;
}
public int getPID() {
return PID;
}
public void setPID(int getPID) {
Integer.toString(PID);
this.PID= PID;
}
public asset(){
Name ="vendor model number";
ID =0;
Serial ="serial number";
Type ="server switch etc.";
PID =1;
System.out.println( Type + "\n " + ID + "\n " + Name + "\n " + Serial + "\n " + PID + "\n ");}
asset(String Type, int ID, String Name, String Serial, int PID){
this.Type= Type;
this.Name= Name;
this.PID= PID;
this.Serial= Serial;
this.ID= ID;
}
public String toString (asset[] a){
getType();
getID();
setID(ID);
getName();
getSerial();
getPID();
setPID(PID);
return this.Type + " " + this.ID + " " + this.Name + " " + this.Serial + " " + this.PID + " ";
}
}
How do i get rid of the "driver.asset#15db9742".
The correct way to override the toString method is to have the following structure :
public String toString(){
// return String type
}
For you (call getXY() does nothing alone) :
public String toString (){
return this.Type + " " + this.ID + " " + this.Name + " " + this.Serial + " " + this.PID + " ";
}
Also, to follow conventions, you'd better :
name classes in CamelCase : asset -> Asset
name attributs (¶meter&variables) follow camelCase : type, id, name, pid
Try this:
int i;
asset basic = new asset();
asset[] server = new asset[2];
server[0]= new asset("server", 10, "server0", "a1", 1);
server[1]= new asset("server", 20, "server1", "a2",1);
System.out.println(basic); // just delete this line.
for (i=0;i<server.length;i++)
{
System.out.println(server[i].Type);
System.out.println(server[i].Name);
System.out.println(server[i].ID);
System.out.println(server[i].Serial);
System.out.println(server[i].PID);}
}
You kept printing out the value of basic, that's probably why it churned out the the string hash name instead of the actual stored value. Just take the System.out.println(basic); out of the for loop? Even better, delete the line altogether!
this is my huge mindblowing problem with a Java exercise. So, we've got this:
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate
}
and our goal is to overwrite toString method by cutting fields which may lead to recursive infinity. Finally it's supposed to look like a printed object with a name, age, boss and subordinate.
Employee[age=30,name='Mike',boss=Employee[age=45,name='Ann'], subordinate=[Employee[age=25,name='Jimmy']]]
Well, I tried and found that i have no clue how to deal with toString overriding:
import java.util.ArrayList;
import java.util.List;
public class CyclicEmployee {
private int age;
private String name;
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
public CyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
public static void main(String[] args) {
CyclicEmployee Mike = new CyclicEmployee(33,"Mike");
Mike.boss = new CyclicEmployee(44,"Ann");
Mike.subordinate = new ArrayList<CyclicEmployee>();
Mike.subordinate.add(new CyclicEmployee(24,"Jim"));
System.out.println(Mike.toString());
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + boss +
", subordinate=" + subordinate +
'}';
}
}CyclicEmployee{age=33, name='Mike', boss=CyclicEmployee{age=44, name='Ann', boss=null, subordinate=null}, subordinate=[CyclicEmployee{age=24, name='Jim', boss=null, subordinate=null}]}
It seems like I should cut all the "null" fields here, but I can't find the way out.
If I understand correctly, you do not want to print null CyclicEmployee objects. You can check if boss and subordinates are null and then if they are skip them in toString(). Since all of them are same type, this method will work for all of them.
#Override
public String toString() {
String str = "";
str = "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'';
if (boss != null) {
str += ", boss=" + boss;
}
if (subordinate.size() != 0) {
str += ", subordinate=" + subordinate;
}
str += '}';
return str;
}
Consider using existing data structure like this or this instead.
But if you really want to use your code, you can create a NonCyclicEmployee class
private static class NonCyclicEmployee {
private int age;
private String name;
public NonCyclicEmployee(int age, String name) {
this.age=age;
this.name=name;
}
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}
}
And use it in your toString() of CyclicEmployee.
private CyclicEmployee boss;
private List<CyclicEmployee> subordinate ;
private NonCyclicEmployee ncBoss;
private List<NonCyclicEmployee> ncSubordinate ;
#Override
public String toString() {
return "CyclicEmployee{" +
"age=" + age +
", name='" + name + '\'' +
", boss=" + ncBoss +
", subordinate=" + ncSubordinate +
'}';
}
And create a method addBoss() and addSubordinate() to create both bosses (boss and ncBoss) and both subordinate at the same time.
I'm trying to make a student class to take in and print some values about a student, but I get a "Invalid Method Declaration" error on line 29 and I have no idea why.
I am trying to contain student creation data inside one method, and a tostring() method in another method.
public class Student {
int ID;
int Age;
String Name;
double AvgLogin;
public Student(int ID,int Age,String Name,double AvgLogin)
{
this.ID = ID;
this.Age = Age;
this.Name = Name;
this.AvgLogin = AvgLogin;
}
public printer(int ID,string Name,int Age,double AvgLogin) {
System.out.println("Age : " + Age + " Average Login time : " + AvgLogin + "ID :" + ID +" Name : " + Name);
} //end method
public int getID() {
return ID;
}
public String getName() {
return Name;
}
public int getAge() {
return Age;
}
public void setAge(int Age) {
this.Age = Age;
}
public double getAvgLogin() {
return AvgLogin;
}
public void setAvgLogin(double AvgLogin) {
this.AvgLogin = AvgLogin;
}
}
//Student John = new Student(ID,Age,Name,AvgLogin)
you just missed the return type for your printer method. You should use the following code for your printer method.
public void printer(int ID,String Name,int Age,double AvgLogin) {
System.out.println("Age : " + Age + " Average Login time : " + AvgLogin + "ID :" + ID +" Name : " + Name);
}
You have two errors in your method. One of them is lack of the return type. Second one is typing string instead of String. Thirdly, it looks nice if you start variable name from lower case. You should also format code before making a question.
public void printer(int id, String name, int age, double avgLogin) {
System.out.println("Age: " + age + ", average login time: " + avgLogin + ", ID: " + id + ", name: " + name);
}
I have a practice problem that I need to complete and have done everything however I cannot get the output to match whats needed. I have tried some of the google answers but nothing seems to be working. Below is the code and the output I get vs what I want. We are not allowed to modify the main method but only the classes.
I am just confused on how to make the output from each class start on a new line.
There is this statement in the instructions but I don't understand how to go about it:
the Student class should have a public display function that calls the parent class’ display
function,
Code:
public class H255{public static void main (String[] args){while (JPL.test()){
Person pObj = new Person("Albert","Einstein");
Student sObj = new Student("John","Smith",123456,"First Year","Pullan");
Teacher tObj = new Teacher("Wayne","Pullan","Computer Science",100000,"Lecturer");
System.out.println("Person :");
pObj.Display();
System.out.println("");
System.out.println("Student :");
sObj.Display();
System.out.println("");
System.out.println("Teacher :");
tObj.Display();
}}}
class Person{
private String FirstName;
private String LastName;
public Person(String fName, String lName){
this.FirstName = fName;
this.LastName = lName;
}
public void Display(){
System.out.println("First Name: " + FirstName + " Last Name: " + LastName);
}
}
class Student extends Person{
private int id;
private String standard;
private String instructor;
public Student(String fName, String lName, int nId, String stnd, String instr){
super(fName, lName);
this.id = nId;
this.standard = stnd;
this.instructor = instr;
}
public void Display(){
System.out.println("ID: " + id + "Standard: " + standard + "Instructor: " + instructor);
}
}
class Teacher extends Person{
private String mainSubject;
private int salary;
private String type;
public Teacher(String fName, String lName, String sub, int slry, String sType){
super(fName, lName);
this.mainSubject = sub;
this.salary = slry;
this.type = sType;
}
public void Display(){
System.out.println("Main Subject: " + mainSubject + "Salary: "
+ salary + "Type: " + type );
}
}
Output:
the writing of main method like these code:
System.out.print("Person :");
pObj.Display();
System.out.print("Student :");
sObj.Display();
System.out.print("Teacher :");
tObj.Display();
because:the println method has a build in wrap feature, so just replace println with print.
I have three classes named Human.java, Superhero.java and Run.java. The Superhero extends Human and the method introduce() is overridden in Superhero with call to parent class's introduce(). But, When I'm making a superhero object and calling the introduce method, it doesn't print the base class method's returned value. What's wrong? Thanks in advance.
Human.java
public class Human implements Comparable<Human> {
private int age;
private String name;
public Human(String givenName, int age) {
this.name = givenName;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String introduce() {
return "Hey! I'm " + name + " and I'm " + age + " years old.";
}
#Override
public int compareTo(Human H1) {
if(this.getAge() > H1.getAge())
return 1;
else if (this.getAge() < H1.getAge())
return -1;
else
return 0;
}
}
Superhero.java
public class Superhero extends Human {
private String alterEgo;
private int age;
private String name;
public Superhero(String givenName, int age, String alterEgo) {
super(givenName, age);
this.alterEgo = alterEgo;
}
public String getAlterEgo() {
return alterEgo;
}
#Override
public String introduce(){
super.introduce();
return "I am also known as " + alterEgo + "!";
}
}
Run.java
public class Run {
public static void main(String[] args) {
Superhero superhero = new Superhero("Bruce", 26, "Batman");
System.out.println(superhero.introduce());
}
}
#Override
public String introduce(){
super.introduce();
return "I am also known as " + alterEgo + "!";
}
The introduce method of the SuperHero class is dumping the String returned by the call to the base method & returning "I am also known as " + alterEgo + "!" instead.
You need to return the result of the concatenation of the String returned by the base class's implementation + the SuperHero-specific string:
#Override
public String introduce(){
return super.introduce() + "I am also known as " + alterEgo + "!";
}
1st: You are calling super.introduce() which returns a string but you are not doing anything with that string. You need to assign it to a variable and add it to your return statement for it to be visible.
2nd: I recommend you change the introduce() method to toString() since that way you can get the string by just writing:
System.out.println(superhero);
Here is what you need to do to return the "Hey! I'm " + name + " and I'm " + age + " years old." part as well:
#Override
public String toString(){
return super.introduce() + "\n" + "I am also known as" + alterEgo + "!";
}
Personally i prefer implementing my toString() methods like this.
#Override
public String toString(){
String string = super.toString();
string = string + "\n";
string = string + "I am also known as";
string = string + alterEgo;
string = string + "!";
return string;
}
The reason your method does not print what's returned from the superclass is that your overriding method drops the return value. Generally, this is OK, so Java does not warn you about that. However, in this case you want to use the return value, so you should not ignore the result of calling the super.introduce() method.
Your method should take that value, and append to it, like this:
#Override
public String introduce(){
return super.introduce() + "\n"
+ "I am also known as " + alterEgo + "!";
}