Print array variables, not variable pointer locations [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 working on a project from a Java text book, and I have come across an issue. I am attempting to print the variables in an array, however it continually prints the variables location (#hex code) instead of the actual variable... I believe I am attempting to print the array correctly via using a 'for loop'. I have attached my code below...
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
}
//Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
}
Any and all guidance is appreciated. Thank You!

You need to override the toString method in your Person class.
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName) { ... }
public String getName() { ... }
public int compareTo(Person o) { ... }
#Override
public String toString() {
return "My name is " + name; // For the example, you could return any String you want
}
}
the toString method is generally used to provide a description of the object.

Related

Array of class objects are null even after initializing them with new keyword [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
NullPointerException when Creating an Array of objects [duplicate]
(9 answers)
Closed 9 months ago.
I have two classes named RRT and MyClass. RRT class has some data members and for each of them it has respective getter and setter method. From the main method of MyClass I am creating an array of RRT objects and trying to set values to data members using the object's setter method but receiving an error saying object is null.
RRT.java
public class RRT {
private int ticketNo;
private String raisedBy;
private String assignedTo;
private int priority;
private String project;
// getters
public int getPriority() {
return priority;
}
public int getTicketNo() {
return ticketNo;
}
public String getAssignedTo() {
return assignedTo;
}
public String getProject() {
return project;
}
public String getRaisedBy() {
return raisedBy;
}
// setters
public void setAssignedTo(String assignedTo) {
this.assignedTo = assignedTo;
}
public void setPriority(int priority) {
this.priority = priority;
}
public void setProject(String project) {
this.project = project;
}
public void setRaisedBy(String raisedBy) {
this.raisedBy = raisedBy;
}
public void setTicketNo(int ticketNo) {
this.ticketNo = ticketNo;
}
}
MyClass.java
class MyClass{
public static RRT getHighestPriorityTicket(RRT[] rrt, String value){
RRT highestPriority = null;
int high = Integer.MAX_VALUE;
for(RRT i : rrt){
if(i.getProject().compareToIgnoreCase(value)==0 && i.getPriority()<high){
high = i.getPriority();
highestPriority = i;
}
}
return highestPriority;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int number = 4;
RRT[] ob = new RRT[number];
for (int i = 0; i <number ; i++) {
String ticketNumber = sc.next();
String raisedBy = sc.next();
String assignedTo = sc.next();
String priority = sc.next();
String project = sc.next();
ob[i].setAssignedTo(assignedTo);
ob[i].setPriority(Integer.parseInt(priority));
ob[i].setRaisedBy(raisedBy);
ob[i].setTicketNo(Integer.parseInt(ticketNumber));
ob[i].setProject(project);
}
String targetProject = sc.next();
RRT answer = getHighestPriorityTicket(ob,targetProject);
if(answer!=null){
System.out.println(answer.getTicketNo());
System.out.println(answer.getRaisedBy());
System.out.println(answer.getAssignedTo());
}
else {
System.out.println("No such Ticket");
}
}
}
Can anyone tell me what is wrong with the code .

NullPointerException in group class. can't find an array object [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
so when i try to run my Group class, it tells me that the content of the student array is null and i cant find where specifically (been spending the last 4 hours trying to figured it out).if you have any questions regarding of classes, dont hesitate to ask.
thanks in advance for all of your answers.
Group class
public class Group {
private Student studentArray[];
private int nbOfStudent;
public Group() {
studentArray[]= new Student[24];
}
public void add( Student stud){
studentArray[nbOfStudent]=stud;
nbOfStudent++;
}
public String toString(){
String msg="";
for(int i=0;i<studentArray.length;i++){
msg+=tabStudent[i]+" ";
}
return msg;
}
public Student getStudentArray(int i) {
return studentArray[i];
}
public Student[] getstudentArray(){
return studentArray;
}
public void setStudentArray[](Student[] studentArray) {
this.studentArray= studentArray;
}
public int getNbOfStudent() {
return nbOfStudent;
}
public void setNbOfStudent(int student) {
this.nbOfStudent = student;
}
public int search(String code){
return UtilsTabs.search(studentArray, code,this.nbOfStudent);
}
public void sort(){
UtilsTabs.sort(studentArray, nbOfStudent);
}
}
UtilsTabs class
public static void sort(Student[] array, int nbOfStud){
Student temp=null;
int minIndex=0;
for(int i=0;i<array.length-1;i++){
minIndex=i;
for(int j=i+1;j<nbOfStud;j++){
int comparedValue = tab[j].compareTo(tab[minIndex]);
if( comparedValue< 0){
minIndex=j;
}
}
temp=tab[i];
array[i]=array[minIndex];
array[minIndex]=temp;
}
}
public static int search(Student array[],String code,int nbofStud){
int pos=-1;
for(int i=0;i<tarray.length;i++){
if(tab[i].getCode().equalsIgnoreCase(code));
pos=i;
}
return pos;
}
Student class
public class Student {
private String code;
private String name;
private Grades evaluation;
public Student(String code, String name, String eval) {
this.code = code;
this.nom = nom;
this.evaluation=new Grades(eval);
}
public Message message(){
if(this.evaluation.gradeAverage()<60)
return Message.FAILED;
else
return Message.SUCCESS;
}
public boolean equals(Student other){
boolean res=this.code.equals(other.code);
return res;
}
public int compareTo(Student other){
int res= this.code.compareTo(other.code);
return res;
}
}
test of class group
Group gr = new Group();
Student stud2 = new Student("26161234", "Marc", "65 81 58 100 79");
gr.add(stud2);
Student stud=new Student("24910003", "Pierre", "45 59 36 66");
gr.add(stud);
//show group of student
System.out.println("Group of students:\n" + gr.toString());
this is what the console shows me
result of test of Group class
Your group.toString is using tabStudent which i cant see getting initialised or used anywhere else

Finding and removing an object from arraylist while not knowing the object's variables

I'm new to Java and i've been bashing my head over the wall to solve this problem. Anyway below is a class that creates a Person and below that, is a class that creates a Phonebook using an ArrayList of type Person. I want to write the remove function (in order to remove a Person from the list) but my problem is that since i only get the name of the person i can't use the Indexof function (cause it requires object) to get at what position lies the name.
This is my first time using an ArrayList to store an Object so i'm not even sure
how my results would appear. I'm guessing that if the position of the name (in my list) is 10 then 11 would be the phone and 12 would be the address. Am i correct?
public class Person
{
private String name;
private String phone;
private String address;
public Person (String n, String p, String a)
{
this.name = n;
this.phone = p;
this.address = a;
}
public void setPhone(String newPhone)
{
this.phone = newPhone;
}
public String getName()
{
return this.name;
}
public String getPhone()
{
return this.phone;
}
public String getAddress()
{
return this.address;
}
public String print()
{
return "Name is : " + this.name + "\nPhone is : " + this.phone + "\nAddress is : " + this.address;
}
}
import java.util.*;
public class phoneBook
{
Scanner in = new Scanner ( System.in );
private ArrayList <Person> persons = new ArrayList <Person>();
private int i;
private boolean flag;
public void addPerson(Person p)
{
persons.add(p);
}
public void listPersons ()
{
System.out.println(persons);
}
public void lookUp (String theName)
{
flag = persons.contains(theName);
if ( flag == true )
{
System.out.println("That name exists!");
}
else
{
System.out.println("That name does not exist!");
}
}
public void remove (String theName)
{
}
Edit: I'm planning to use the Scanner in another function. Don't worry about it.
I'm not sure of if do you want to get the object of that array, but each object is indexed to that array (with full attributes), now you can remove it by using the following code,
public String removePerson(ArrayList<Person> arrayList,String name)
{
for(Person currentPerson:arrayList)
{
if(currentPerson.getName().equals(name))
{
arrayList.remove(currentPerson);
return "Removed successfully"
}
}
return "No record found for that person";
}
just pass the arrayList and the name of that person to this method
You should override the equals() and hashCode() methods in the Person class. This way you will define when two objects of this type will be considered equal. Then you can use list.contains(yourObject) to determine if that object is equal to any object in your list, this based on your equals() implementation.
Does this help you?
public void remove (String theName,ArrayList<Person> persons) {
for (int i = 0; i < persons.size();++i) {
if(persons[i].getName().equals(theName)) {
persons.remove(i);
}
}
}
Best regards, Nazar

Value added to array is NULL?

In my code below, I am experiencing a problem I am unable to get around... when I add a class Person object to an array, it appears to add fine, however when I attempt to print out that object value form a specified array position, it outputs "null."
Here is the code
import java.util.Scanner;
import java.util.Arrays;
import java.lang.String;
public class Main
{
public static void main(String[] args)
{
int ARRAY_LENGTH = 2;
Scanner in = new Scanner(System.in);
Person[] Persons;
Persons = new Person[ARRAY_LENGTH];
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println("Enter a name to add to the array: ");
Persons[i] = new Person(in.next());
System.out.println(Persons[i]);
}
Arrays.sort(Persons);
for (int i = 0; i < ARRAY_LENGTH; i++)
{
System.out.println(Persons[i]);
}
}
}
&
public class Person implements Comparable<Person>
{
private String name;
public Person (String aName)
{
String name = aName;
}
public String getName()
{
return name;
}
public int compareTo(Person o)
{
Person other = (Person) o;
if (this.name.equals(o.name))
{
return 0;
}
if (this.name.compareTo(o.name) < 0)
{
return -1;
}
return 1;
}
#Override
public String toString()
{
return name;
}
}
No, it hasn't added null to the array. It's put a reference to a Person object in the array, and when you call toString() on that Person object, it's returning the value of the name field... which is always null, because of this constructor:
public Person (String aName)
{
String name = aName;
}
That isn't assigning a value to the name field - it's declaring a local variable called name. (I'd expect a decent IDE to issue a warning about that.)
You want:
public Person (String aName)
{
name = aName;
}
The constructor
public Person (String aName)
{
String name = aName;
}
stores the name in a local variable.
Change this to
public Person (String aName)
{
this.name = aName;
}
The constructor is wrong
public Person (String aName)
{
String name = aName;
}
it is creating a new variable instead of assigning the field properly.
Try removing the type declaration:
public Person (String aName)
{
name = aName;
}

How can I use a method to change a value? [duplicate]

This question already has answers here:
Can I pass parameters by reference in Java?
(8 answers)
Closed 8 years ago.
class Trial {
static void main() {
int i = 0;
change(i);
System.out.println(i);
}
static void change(int n) {
n = n + 2;
}
}
Output I'm getting - 0
Output I want - 2
Please help me change my code.
Everything in Java is pass by value:
http://www.javaranch.com/campfire/StoryPassBy.jsp
Try this instead:
class Trial {
static void main() {
int i = 0;
i = change(i);
System.out.println(i);
}
static int change(int n) {
return n + 2;
}
}
Edit
A parameter to a method is given a copy of the value. This value will either be a raw value (primitive) or an object reference (object).
For objects, a copy of the reference means you can change the state of an object within a method. What you cannot do is change the state having changed what the parameter is referring to.
Example 1:
class Person {
private String name;
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
}
Person p = new Person("James");
changeName(p);
System.out.println(p.getName()); // This will output Changed
...
public void changeName(Person person) {
person.setName("Changed");
}
Example 2:
Person p = new Person("James");
changeName(p);
System.out.println(p.getName()); // This will output James
...
public void changeName(Person person) {
person = new Person(); // person is now referring to new object, not the one passed
person.setName("Changed");
}

Categories