Printing out an object[] in java? [duplicate] - java

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
I am trying to print out an array of the object Teacher that I have created, and its giving me a weird output.
[Teacher#659e0bfd, Teacher#2a139a55, Teacher#15db9742, Teacher#6d06d69c, Teacher#7852e922]
I have had this problem before where I was trying to use toString() on a 2d array, but I am now using a 1d array of objects. I have tried using both deepToString() and toString(), but it still gives output like that. I tried looking up how to print out an array of Objects, but all I find is how to print out a regular array.
My Code:
import java.util.Arrays;
public class Main {
public static void main(String[] args){
Teacher[] teachers = new Teacher[5];
Student[] students = new Student[25];
createTeacherNames(teachers);
System.out.println(Arrays.toString(teachers));
}
public static void createTeacherNames(Teacher[] teachers){
teachers[0] = new Teacher("Mrs.", "Smith", 201);
teachers[1] = new Teacher("Mr.", "Johnson", 202);
teachers[2] = new Teacher("Mrs.", "Williams", 203);
teachers[3] = new Teacher("Mr.", "Brown", 204);
teachers[4] = new Teacher("Mr.", "Jones", 205);
}
}
Person Class:
public class Person {
public String firstName;
public String lastName;
public Person(String firstName, String lastName){
this.setFirstName(firstName);
this.setLastName(lastName);
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
Teacher Class:
public class Teacher extends Person {
public int roomNumber;
public Teacher(String firstName, String lastName, int roomNumber) {
super(firstName, lastName);
}
}
Student Class:
public class Student extends Person {
public Student(String firstName, String lastName, int studentIdNumber, double GPA) {
super(firstName, lastName);
}
}

In your Teacher class, override toString(), similar to this:
#Override
public String toString() {
String out = "";
out = "[" + teacherPrefix + "," + firstName + "," + idNum + "]";
return out;
}
Would return something like:
//[Mrs.,Smith,201]
It may be better to use a StringBuilder, but you can work out what you need from my example.

You should create a custom toString() method (override the default toString() method of Teacher class). Teacher#659e0bfd is the object identifier and is returned by the default toString() method of an object.
It might look something like this:
public String toString()
{
return super.getFirstName() + " " super.getLastName() + " " + this.roomNumber;
}

Related

How to write a method that reads particular content in an array lists and count the number of array's content

I am a new learner and I should create a method that will make this program work with no problems at all so I can get the :::final result that should look like this:::
3 is 3
Mark is Mark
Richard is Richard
Here is the code (PLEASE read the comments I wrote in the code)
public class Main {
/*I wrote the following method (Student) but I keep get some issues:
Please help I spend many days and I can't figure it out and I am runnung out
of time as I should understand the problem or at least the correction that I
can read and figure out what I was doing wrong.*/
// My written code starts here
public static String Student(String[] sx){
int counter = 0;
for (int i = 0; i < sx.length; i ++){
if (sx[i] != null) counter ++;
}
return counter;
sx = new String[counter];
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
Check the following code snippet
import java.util.List;
public class Main {
// My written code starts here
static class Student {
String firstName;
String middleName;
String lastName;
// Constructor for setting the class variable with all 3 field
public Student(String firstName, String middleName, String lastName) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
}
// Constructor for setting the class variable with 2 field
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
//to get the FirstName field of a student object
public String getFirstName() {
return firstName;
}
//to set the FirstName field of a student object
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static int getTotalStudents() {
// this is wrong way of doing this.
// You should ideally send a list Of Student to know the number of students as shown below
return 3;
}
public static int getTotalStudentsFromList(List<Student> studentList) {
return studentList.size();
}
}
// My written code ENDS here
// From this point I should preserve the code without any changes
static Student studentA;
static Student studentB;
static Student studentC;
public static void main(String[] args) {
studentA = new Student("Mark", "John", "Jimmy");
studentB = new Student("Will", "George", "Androw");
studentC = new Student("Frank", "Sam");
int totalStudents = Student.getTotalStudents();
System.out.println(totalStudents + " is 3");
System.out.println(studentA.getFirstName() + " is Mark");
studentA.setFirstName("Richard");
System.out.println(studentA.getFirstName() + " is Richard");
}
}
I have added possible comments to explain the code. Let me know if you feel any difficulty in understanding this.

How to get output objects on screen?

I am working on an assignment where I must instance several different objects and format them on the screen. I am having trouble getting the strings to output properly; in place of text I get an output like this
run:
First Name Last Name Student ID Number
studentdemo.StudentDemo#6d06d69c
studentdemo.StudentDemo#7852e922
studentdemo.StudentDemo#4e25154f
studentdemo.StudentDemo#70dea4e
studentdemo.StudentDemo#5c647e05
BUILD SUCCESSFUL (total time: 0 seconds)
Here is my main
package studentdemo;
public class MainStudent {public static void main(String[] args) {
StudentDemo student1 = new StudentDemo("Peter\t","Adams\t","123546\t");
StudentDemo student2 = new StudentDemo("James\t","Clark\t","654332\t");
StudentDemo student3 = new
StudentDemo("Christopher\t","Colombo\t","223344\t");
StudentDemo student4 = new StudentDemo("Amy\t","Tan\t","997766\t");
StudentDemo student5 = new
StudentDemo("Marry\t","Madison\t","6543321\t");
System.out.println("First Name\t"+"Last Name\t"+"Student ID Number\t");
System.out.println(student1);
System.out.println(student2);
System.out.println(student3);
System.out.println(student4);
System.out.println(student5);
}
}
and here is my other class
package studentdemo;
public class StudentDemo {
private String firstName;
private String lastName;
private String studentIdNumber;
public StudentDemo(String firstName, String lastName, String
studentIdNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.studentIdNumber = studentIdNumber;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setStudentIdNubmer(String studentIdNumber) {
this.studentIdNumber = studentIdNumber;
}
public String getStudentIdNumber() {
return studentIdNumber;
}
}
What am I doing wrong?`
This is because you are trying to print the object (student1) instead of the properties of object.
Please try:
System.out.println(student1.getFirstName()+"\t"+student1.getLastName()+"\t"+student1.getStudentIdNumber());
instead of:
System.out.println(student1);
Hope this will solve your problem.
You need to output like so:
System.out.println(student1.getFirstName() + " " + student1.getLastName());
A better solution would be to override the toString() method in your StudentDemo class. For example:
public class StudentDemo {
...
#Override
public String toString() {
return this.firstName + " " + this.lastName + " " + this.studentIdNumber;
}
}
Now when you create a new student object, ie StudentDemo student1 = new StudentDemo();, if you do System.out.prntln(student1);, the toString() method will automatically be called.

Creating a method where two objects are considered equal if the first and last names are the same.

So within this class, I need to create a Equals method that will check to determine if the two objects have the same name. I tried creating the two objects within the class and just initialize it with "" for the constructor, but it gave an error on the created objects
Person.Java
public class Person
{
String firstName = "";
String lastName = "";
String age = "";
public Person (String firstName, String lastName, String age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public String getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(String age){
this.age = age;
}
public String toString(){
return firstName + " " + lastName + ", " + age + " years old";
}
}
Here is my driver, so basically I need a method that sees both have the same name and prints out a message saying that they have the same name. My lab states it has to be in the class NOT the driver, which is why I'm lost considering I could easily make an if/else statement within the driver.
public class PersonDriver
{
public static void main(String[] args)
{
Person p1 = new Person("John","Doe", "42");
Person p2 = new Person("John","Doe", "43");
System.out.println(p1);
System.out.println(p2);
}
}

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;

Creating a class with different argument lengths

How do I create a class that has different lengths of arguments?
public static void main(String[] args) {
group g1 = new group("Redskins");
group g2 = new group("Zack", "Mills", 21);
group g3 = new group("John","Smith",20);
group g4 = new group("Fred","Fonsi",44);
group g5 = new group("Jeb","Bush",26);
System.out.println(g1.getName());
}
}
I want to be able to display the team name (redskins) and then each member after that using one method.
I've tried using two methods and got that to work, but can't get one.
I was thinking about possibly using an array but not sure if that would work.
Thanks for any help.
I have three classes the main, student, and group.
I need the group class to display the group name and then figure out how to display the students information underneath. The only thing, is that my assignment is vague about whether I can use two methods or one.
public class student {
String firstName;
String lastName;
int age;
student(String informedFirstName, String informedLastName, int informedAge){
firstName = informedFirstName;
lastName = informedLastName;
age = informedAge;
}
String getName()
{
return "Name = " + firstName + " " + lastName + ", " + "Age = " + age;
}
}
public class Team{
String name;
Set<Player> players;
public Team(String name){
this.name = name;
}
public void addPlayer(Player p){
players.add(p);
}
}
public class Player{
String name;
etc
}
EDIT for revised question:
Ok, Im going to show a lot here. Heres what a proper Java versio of what you want for student.
public class Student {
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/*
* Use:
* Student s = new Student(Bill, Nye, 57);
* System.out.println(s.toString());
*/
#Override
public String toString() {
return "First Name: " + firstName + ", Last Name: " + lastName + ", Age: " + age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The Things to take away from this.
1) Capitalize the first letter of class names! (Student)
2) note the class variables are private (look here for a tutorial Java Class Accessibility) and have getters and setter to control access outside the class.
3) I dont say "getName()" and return name and age. This doesnt make sense. Instead i make it so when you go toString() it shows all the relevant information.
4) Java is an object oriented language which means the classes that model data are supposed (to some extent) model appropriately to the way they are used in real life. This makes it more intuitive to people reading your code.
5) if your Group class (note the capital!) needs to contain many Students use a LIST such as an ArrayList. Arrays would make no sense because you dont know how many Students are going to be in each Group. A SET like i used above is similar to a list but only allows ONE of each item. For simplicity use a list though
6) the THIS operator refers to class (object) variables. In the constructor this.firstName refers to the firstName within the Class (object...an instance of the class) whereas just firstName would refer to the variable in the contructor and not alter the class variable.
use the constructor for that
class group {
String fname,lname;
group(String fname ){
this.fname=fname;
}
group(String fname,String lname){
this.fname=fname;
this.lname=lname;
}
group(String fname,String lname,int age){
this.fname=fname;
this.lname=lname;
this.age=age;
}
public String getName(){
return fname+lname+age;
}
}

Categories

Resources