My arraylist is displaying object address not object contents [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
arraylist displays object address not actual object , program usesinheritance where salesEmployee is the super class and salesAgent and salesPerson are the subclasses.
import java.util.Scanner;
import java.util.ArrayList;
public class tester {
public static void main(String[]args ) {
ArrayList <salesEmployee> listemps= new ArrayList <salesEmployee>();
Scanner user_input= new Scanner(System.in);
salesPerson emp1 = new salesPerson();
emp1.setName("Frank Long");
emp1.setppsNumber(65783);
System.out.println("Enter total value of sales earned by Frank Long");
double valeSale;
valeSale=user_input.nextDouble();
emp1.setvalSale(valeSale);
emp1.getCommission();
listemps.add(emp1);
for ( int j=0; j<listemps.size(); j++ )
System.out.println("element " + j + ": " + listemps.get(j) );
}
}
This is my salesPerson class
public class salesPerson extends salesEmployee{
public salesPerson() {
}
public salesPerson(String name, int ppsNumber, double valSale, double commission) {
super(name, ppsNumber,valSale,commission);
}
public void getCommission() {
commission=valSale*0.15;
}
public String toString2() {
return toString1()+"value of sales"+getvalSale()+"commission:"+commission;
}
}
I'll make it more elegant later for now I am just trying to get it to work
Updated: Based on the comments to my answer, there is a different issue at play. Here's what was added in the comments:
Enter total value of sales earned by Frank Long 22.00
Exception in thread "main" java.lang.StackOverflowError at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) at
salesPerson.toString(salesPerson.java:21) – lucylio 5 mins ago
Is what comes up – lucylio 5 mins

In order for something reasonable to be displayed, you need to implement toString method in your class. You do have toString1 and toString2, but seemingly, no toString. (You haven't posted the code for salesEmployee class - but most likely it also doesn't have toString implementation).
In absence of toString, default Object.toString is called, which displays the address of the object.
Implement toString - and you'll see your results.
UPDATE: As the error you indicated doesn't correspond to the code, I'll go on a whim and suggest that, probably your toString2 method is actually toString and your toString1 method is actually a toString defined in your parent class, i.e. salesEmployee.java. In this case, instead of calling toString() from inside your toString method, use super.toString() instead:
public class salesPerson extends salesEmployee {
...
public String toString2() {
return super.toString()+"value of sales"+getvalSale()+"commission:"+commission;
}
}

Related

Storing and then Printing data to/from and Array list of a class [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 5 years ago.
Class File:
public class Student {
public String stu_FName;
public String stu_LName;
public String stu_ID;
}
This is the code I wrote to get inputs from the user
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for X");
int x = sc.nextInt();
ArrayList<Student> stuIDArray = new ArrayList<Student>(4);
while (x != 0) {
Student st = new Student();
System.out.println("Enter First Name");
st.stu_FName = sc.next();
stuIDArray.add(st);
System.out.println("Enter value fo1r X");
x = sc.nextInt();
}
When I print the size of the array after storing values using the above code, size works fine,
System.out.println(stuIDArray.size());
but when i try to print out the results in any of the following methods, it prints some code type format
for (int i=0;i<stuIDArray.size();i++){
System.out.println(stuIDArray.get(i));
}
for (Student a : stuIDArray){
System.out.println(a);
}
output :
com.company.Student#45ee12a7
com.company.Student#330bedb4
com.company.Student#45ee12a7
com.company.Student#330bedb4
You need to specify name of the variable you need to get data for. Below code is working fine.
for (int i = 0; i < stuIDArray.size(); i++) {
System.out.println(stuIDArray.get(i).stu_FName);
}
for (Class1 a : stuIDArray) {
System.out.println(a.stu_FName);
}
This would happen because when you are trying to print the student "object", it would print the string representation of the student object.
What you need to do is to override the toString method in Student class with proper properties somewhat like,
#Override
public String toString() {
return "Student [stu_FName=" + stu_FName + ", stu_LName=" + stu_LName
+ ", stu_ID=" + stu_ID + "]";
}
You have to learn about toString() method. When you try to use System.out.println() on an object, its toString() method is invoked, and the signature you've been getting, e.g. com.company.Student#330bedb4 is the default return value of those methods, as explained here. If you'd like a proper detail of each field, override the toString method in your Student class. For more, check out this answer

Array prints memory address despite Override [duplicate]

This question already has answers here:
I am getting the memory address from an arraylist, need info
(2 answers)
Closed 8 years ago.
Now, I want it to only print what it says, without the memory address as well. How would I achieve that?
public Telefonnummer[] getTelenummer() {
Telefonnummer[] tnummer = new Telefonnummer[nummerarray.size()];
nummerarray.toArray(tnummer);
System.out.println(Arrays.toString(tnummer) );
return tnummer;
}
Is the constructor and:
private static void kundSök() {
System.out.println("...? ");
String namn = keyboard.nextLine();
if (kunderna.containsKey(namn)) {
for (String k : kunderna.keySet()) {
Kund kund = kunderna.get(k);
System.out.println(kund);
System.out.println(kund.getTelenummer());
After i have added a person to the ArrayList etc it gives me an output of:
Sam wasdfgn
[123456: efdg]
[LTelefonnummer;#28d93b30
The last part, memory address bit, is the part I want to get rid of.
Yet again, how do i achieve that?
Edit: I tried to Override, but it did not do anything at all. Could there be another problem?
The default behaviour for toString is to print the type name (as L followed by the type name), followed by # and the hexString of the hashCode (which by default is the memory address for the object).
To change this, override the toString method for your Telefonnummer class.
public class Telefonnummer {
private String nummer;
...
#Override public String toString() {
return "Dial " + nummer + " for a good time";
}
}
Guava library has Joiner which can be used for that. See https://code.google.com/p/guava-libraries/wiki/StringsExplained
String str = Joiner.on(",").join(list);
You also have to have working toString function on class for elements of the list

Java-OOP I keep on getting this strange output

I am currently taking Computer Science at school and I am a bit stuck on my lab.
The directions are listed below and we are required to use an OOP.
The problem is that my output that I get is super strange and I really don't know what is going on.
The output that I get after running the file DiscountRunner.java (code listed below) is:
Enter the original bill amount :: 4000
Discount#1d1be4e
Why do I keep on getting the Discount#1d1be4e part?
/**==================================================================================================
* Objective : This lab was designed to teach you how to use if statements.
* Lab Description : Determine the amount of discount a person should receive.
* If the bill is more than 2000, then the person should receive a 15% discount.
* If the bill is 2000 dollars or less, the person does not receive a
* discount of any kind.
===================================================================================================*/
import static java.lang.System.*;
import java.util.Scanner;
public class DiscountRunner
{
public static void main( String [] args )
{
Scanner keyboard = new Scanner(System.in);
out.print("Enter the original bill amount :: ");
int amt = keyboard.nextInt();
int Discount;
Discount bill=new Discount();
bill.getDiscountedBill();
System.out.println(bill);
//instantiate a new Discount object called "bill"
//print the output of bill.getDiscountedBill() with amt as the parameter
}
}
That is file one.
Here is file two.
import static java.lang.System.*;
import java.util.Scanner;
public class Discount
{
//instance variables and constructors could be used, but are not really needed
int amt;
int bill;
//getDiscountedBill() will return final amount of the bill
// if the bill is >2000, the bill receives a 15% discount
public int getDiscountedBill()
{
if ( amt>2000)
bill=amt*(int).85;
if ( amt<=2000)
bill=amt*1;
return bill;
}
}
System.out.println() method will try to convert a object to a string before printing it out. In order to do this it will normally call Object.toString() method. The default implementation of said method is to generate a string containing the object type concatenated with the in-memory address of the object. This is what is happening to you.
To fix it you need to provide a toString() implementation to the Discount method.
You get this because of this line:
System.out.println(bill);
You are printing the object which calls the default toString() implementation of Discount (inherited from Object). You can overwrite toString() in Discount to get a custom representation but I guess you just want to remove this System.out statement there.
You had some little mistakes of Type conversions and some in receiving value from method.
Find below the working code
import static java.lang.System.*;
import java.util.Scanner;
public class DiscountRunner
{
public static void main( String [] args )
{
Scanner keyboard = new Scanner(System.in);
Discount bill=new Discount();
out.print("Enter the original bill amount :: ");
bill.amt = keyboard.nextInt();
int discount;
discount=bill.getDiscountedBill();
System.out.println(discount);
//instantiate a new Discount object called "bill"
//print the output of bill.getDiscountedBill() with amt as the parameter
}
}
import static java.lang.System.*;
import java.util.Scanner;
public class Discount
{
//instance variables and constructors could be used, but are not really needed
int amt;
int bill;
//getDiscountedBill() will return final amount of the bill
// if the bill is >2000, the bill receives a 15% discount
public int getDiscountedBill()
{
if ( amt>2000)
**bill=(int)(amt*.85);**
if ( amt<=2000)
bill=amt*1;
return bill;
}
}
Let me know if you are not getting something.
Accept the answer if it solves your Problem.
You didn't override the toString() method in the Discount class which is inherited by the Java class Object. This causes the output you listed.
Whenever you pass a Object to System.out.println it executes its toString method, Default implementation of toString prints ClassName with its hashCode. you can override toString method. add below code snnipet to your Discount Class and it will run as per your expectation
#Override
public String toString()
{
return "Bill Amount After Discount is " + bill ;
}

Print Array of Objects in BlueJ [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 6 years ago.
For an assignment, I was asked to work on calling a class and creating an array objects, which i did here;
public void DVDArrayObjects() {
//creates variables
int i;
DVDClass[] dvdArray = new DVDClass[5];
//reference to DVDClass
for (i = 0; i < 2; i ++) {
//create new instance of calling the class
dvdArray[i] = new DVDClass();
//create new instance of getting the info
dvdArray[i].getDVDInfo();
//display
//System.out.println(dvdArray[i]);
}
}
Creating the array of objects works fine, but displaying doesn't. it shows the memory allocation when i run it. I'm really stuck as to how to get it to display.
** EDIT **
When i use System.out.println(dvdArray[i].getDVDInfo()); the error void types not allowed in here shows up
** END OF EDIT **
Any help at all would be greatly appreciated.
Print the DVD info (assuming that it returns a string).
System.out.println(dvdArray[i].getDVDInfo());
If it doesn't return a string, you need to override the toString() method on the class DVDInfo like this.
#Override
public String toString()
{
return "Film Name\t: " + filmName +
"\nFilm Director\t: " + filmDirector +
"\nRun Time\t: " + runTime +
"\nLead Actor\t: " + leadActor;
}
Hope this helps.
You need to override the toString() method.
public class DVDCLass {
#Override
public String toString(){
return // whatever you want the output to be
}
}
Override toString() method in your DVDClass class
do like below
class DVDClass{
public String toString(){
return // whatever you want the output to be
}
}

Java Array List get

I am trying to get this program to get the passwords from an array list.
import java.util.ArrayList;
public class CompanyDatabase {
public ArrayList<Person> getPeople() {
ArrayList<Person> people = new ArrayList<Person>();
String[] u = {"Joe","Stan","Leo","John","Sara","Lauren"};
String[] p = {"pass4321", "asdfjkl", "genericpw", "13579", "helloworld", "companypass"};
for(int j = 0; j < u.length; j++){
Person temp = new Person(u[j],p[j]);
people.add(temp);
}
return people;
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class CompanyDatabaseDriver {
private static Scanner scan = new Scanner( System.in ) );
public static void main(String args[]) {
CompanyDatabase bcData = new CompanyDatabase();
ArrayList<Person> people = bcData.getPeople();
// what i tried
System.out.println(bcData.getPeople());
// also tried this
System.out.println(people.get(1));
}
}
The output is
[Person#1c9b9ca, Person#c4aad3, Person#1ab28fe, Person#105738, Person#ce5b1c, Person#1bfc93a]
or just
Person#1995d80
for the 2nd thing I tried.
The specific number / letter combination seems to change each time the program is run. Is there a way to specify which string to display from the array list?
Override toString() in the Person class
What you are seeing is the String returned by Object's default toString() method which is the name of the class followed by its hashcode. You will want to override this method and give the Person class a decent toString() method override.
e.g.,
// assuming Person has a name and a password field
#Override
public String toString() {
return name + ": " + password; // + other field contents?
}
Edit: if you only want to display one field in your output, then use Dave Newton's good solution (1+).
Yes; print the object property you want to see:
out.println(people.get(0).getFirstName());
the default implementation when you print List is to call toString for all objects in this List. and because you don't override toString method, it will call the default toString from Object class, that will print objects hashCode in hexadecimal notation, so you get this result:
Person#1c9b9ca ( classname#hashcode) , and it can be changed every time you execute the application because this hashcode come from memory address of the object).
so one option, is to override toString in your class
#Override
public String toString() {
return String.format("First name %s, Last name %s", firstName, lastName);
}
and call
System.out.println(yourList); // this will print toString for each object
the other option, is to print these attributes when you iterate on the List
for(Person person: persons) {
System.out.println("Person first name: " + person.getFirstName() + " , Last Name: " + person.getLastName());
}
In the first print statement you are trying to print the object..that is why you always see different number/letter combination..

Categories