overriding tostring() method and passing object reference without getting hash - java

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 (&parameter&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!

Related

Simple database on Java

I've got a task to make a simple database on a topic "basketball team" with functionality such as: deleting by ID, inserting new data, modification of information, printing all data from a file. All information should be written in a file.
I've already created createTeam() method that makes a kind of template of my default data that writes in a file.
Basically, after that, I've got trouble in deleteByID() method with deleting exact data that I need, so I'm asking you for a help
My code:
import java.io.*;
public class ChicagoBulls {
static class Player{
private int Id;
private int Age;
private String Name;
private String Surname;
private int Height;
private int Salary;
private String KPI;
private String Shoes;
private int Goals;
Player(int id, int age, String name, String surname, int height,
int salary, String kpi, String shoes, int goals) {
Goals = goals;
Id = id;
Age = age;
Name = name;
Surname = surname;
Height = height;
Salary = salary;
KPI = kpi;
Shoes = shoes;
}
public String getShoes() {
return Shoes;
}
public void setShoes(String shoes) {
Shoes = shoes;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
public String getKPI() {
return KPI;
}
public void setKPI(String KPI) {
this.KPI = KPI;
}
public int getHeight() {
return Height;
}
public void setHeight(int height) {
Height = height;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getSurname() {
return Surname;
}
public void setSurname(String surname) {
Surname = surname;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public int getGoals() {
return Goals;
}
public void setGoals(int goals) {
Goals = goals;
}
}
public void createTeam(int quantity) throws Exception {
File newFile = new File("NewFile.txt");
FileWriter newFileReader = new FileWriter(newFile);
BufferedWriter bufferedWriter = new BufferedWriter(newFileReader);
bufferedWriter.write("|ID|\t"
+ "| AGE |\t"
+ "| NAME |\t"
+ "| SURNAME |\t"
+ "| HEIGHT |\t"
+ "| SALARY |\t"
+ "| KPI |\t"
+ "| SHOES |\t"
+ "| Goals |\t\n");
int counter = quantity;
for (int i = 0; i <= quantity; i++) {
Player defaultPlayer = new Player(i, 19, "DefName", "DefSurname", 180, 6000, "Good", "Nike", 0);
if (defaultPlayer.getId()<=9) {
bufferedWriter.write("|0" + defaultPlayer.getId() + "|\t");
bufferedWriter.write("|" + defaultPlayer.getAge() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getName() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSurname() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getHeight() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSalary() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getKPI() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getShoes() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getGoals() + " |\t");
}else{
bufferedWriter.write("|" + defaultPlayer.getId() + "|\t");
bufferedWriter.write("|" + defaultPlayer.getAge() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getName() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSurname() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getHeight() + " |\t");
bufferedWriter.write("|" + defaultPlayer.getSalary() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getKPI() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getShoes() + " |\t");
bufferedWriter.write( "|" + defaultPlayer.getGoals() + " |\t");
}
bufferedWriter.newLine();
}
bufferedWriter.close();
newFileReader.close();
}
public void deleteByID(int id) throws Exception {
FileReader file = new FileReader("NewFile.txt");
BufferedReader bufferedReader = new BufferedReader(file);
String idLine = bufferedReader.readLine();
int idIndex = idLine.indexOf(id);
int nextIdIndex = idLine.indexOf(id + 1);
}
}
Main
public class Main {
public static void main(String[] args) throws Exception {
ChicagoBulls team = new ChicagoBulls();
team.createTeam(30);
}
}
Thank you in advance.
I think the logic behind your execution is a bit too complicated to be understood without further explanations on your part. From what i gathered on your needs, i would suggest creating multiple constructors for the Player class - one requiring no input and returning a "Default" player with default characteristics, the other one with the ability to specify goals, shoes, etc.
After that, each of your teams can be represented as a Set<> of players. This would make iterating for each of the elements (players) easier, as well as provide a natural way of removing players from the team. You can read more about the implementation of this structure in the Java documentation here.

Java custom toString function error

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

How to print contents of a class object by field?

I have a POJO class, Location that is used to map a JSON file to a class using Jackson. The current implementation can print out every Location object in the class by calling,Location's toString() but I'm wondering how I can print for example, just the location with id= "2", which would be name="Desert"
At the moment, I use a toString method like this to print all the contents of Location:
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
Does anyone know how I can print specific locations within the Location object based on a field id?
This is an example of what is stored in the Location class when I call toString() on it:
http://hastebin.com/eruxateduz.vhdl
An example of one of the Locations within the Location object:
[Location [location=null, id=1, description=You are in the city of Tiberius. You see a long street with high buildings and a castle.You see an exit to the south., weight=100, name=Tiberius, exit=[Exit [title=Desert, direction=South]]]
This is the POJO location class I use to map the JSON fields to the class:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
public boolean isGoalLocation() {
return goalLocation;
}
public void setGoalLocation(boolean goalLocation) {
this.goalLocation = goalLocation;
}
public int getApproximateDistanceFromGoal() {
return approximateDistanceFromGoal;
}
public void setApproximateDistanceFromGoal(int approximateDistanceFromGoal) {
this.approximateDistanceFromGoal = approximateDistanceFromGoal;
}
public Location getParent() {
return parent;
}
public void setParent(Location parent) {
this.parent = parent;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
You need the above dependency to define predicate unless you want to do it on your own.
public class Location {
private int id;
// more stuff here
private Predicate<Integer> filter;
public Location() {
this.filter = TruePredicate.INSTANCE;
}
public Location(int idFilter) {
this.filter = new EqualPrediate(idFilter);
}
public String toString() {
StringBuilder buffer = new StringBuilder();
if(filter.apply(this.id)) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
}
This code is a simplified Visitor Pattern where the
'Visitor' -> your predicate
'this' -> 'this.id'
This works because your toString() is invoking the toString() of the nested Location objects which also have their predicates for filtering set.
If you aren't in control of their construction where you can propogate the filter then you can take this approach:
public String toString() {
StringBuilder buffer = new StringBuilder();
int i = 0;
for(Location l = this; i < locations.length; l = locations[i++])
if(filter.apply(l.id) {
buffer.append("Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]");
}
return buffer.toString();
}
Stream.of(location).filters(l -> l.getId() == 2).foreach(System.out::println);
Does that work?
You can have a try with gson, which inputs a object and outputs a JSON or in the opposite side.
After u make the object a JSONObject, you can ergodic the JSON in order to ergodic object.

Mutator methods not storing values for the class that I have just made?

Here is the class:
package employee;
public class Employee
{
private String name, department,position;
private int idNumber;
public Employee(String n, int id, String depart,String pos)
{
n= name;
id=idNumber;
depart=department;
pos=position;
}
public Employee(String n, int id)
{
n= name;
id=idNumber;
department="";
position="";
}
public Employee()
{
name="";
idNumber=0;
department="";
position="";
}
public void setName(String n)
{
n=name;
}
public void setDepartment(String depart)
{
depart=department;
}
public void setPosition(String pos)
{
pos=position;
}
public void setId(int id)
{
id=idNumber;
}
public String getName()
{
System.out.println();
return name;
}
public String getDepartment()
{
return department;
}
public String getPosition()
{
return position;
}
public int getId()
{
return idNumber;
}
}
Here is the program:
package employee;
public class RunEmployee
{
public static void main(String[] args)
{
Employee first= new Employee();
first.setName("Susan Myers");
first.setId(47899);
first.setDepartment("Accounting");
first.setPosition("Vice President");
Employee sec= new Employee("Mark Jones",39119,"IT","Programmer");
Employee third= new Employee("Joy Rogers", 81774);
third.setDepartment("Manfacturing");
third.setPosition("Engineer");
/*Printing employee ones information*/
System.out.print("Employee #1- using the no-arg constructor.");
System.out.println("Name: " + first.getName());
System.out.println("Id Number: "+ first.getId());
System.out.println("Department: " + first.getDepartment());
System.out.println("Position: "+ first.getPosition());
/*Printing employee twos information*/
System.out.println("Name: " + sec.getName());
System.out.println("Id Number: "+ sec.getId());
System.out.println("Department: " + sec.getDepartment());
System.out.println("Position: "+ sec.getPosition());
/*Printing employee threes information*/
System.out.print("Employee #3- using a constructor that accepts the name"
+ "and ID number only.");
System.out.println("Name: " + third.getName());
System.out.println("Id Number: "+ third.getId());
System.out.println("Department:" + third.getDepartment());
System.out.println("Position: "+ third.getPosition());
}
}
For this project, I am simply trying to store values into the constructor in different ways. However, my output is showing that my mutator methods are not storing any values. I tried to post my output but I do not have the reputation points. Basically, all the the values for the things I tried to arguments say zero or null.
You've got your assignments backwards!
n = name; puts the value of name to n, not the other way around.
You are assigning the value from the Employee instance to your passed in parameters. To prevent that, it is probably a good idea to use this -
this.name = n; // <-- assign n to the name field of the current instance.
In your example code, this.n would have given you a compile time error.

Trouble with inner class, toString confliction

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

Categories