Value added to array is NULL? - java

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

Related

Hiring a person by surname

Could anyone help me fix the below-attached code? I've written a Java method that hires a person by surname, and what I mean by that is that the value passed in the method should be the last name of an object reference (an object of a class Employee which we desire to hire in the company).
However, the program is complaining that the surname cannot be resolved to a type. Now, getSurname() is a method of a private instance variable defined in Employee which is an abstract class (and a superclass for two subclasses Worker and Officer, but that's irrelevant to the problem). Anyone willing to give me a hand?
public class CompanyArrayList {
private ArrayList<Employee> arrayList;
public CompanyArrayList(int employeeNumber) {
ArrayList<Employee> arrayList = new ArrayList<Employee>(employeeNumber);
}
public String hire(Employee employee.getSurname()) { // the object of this class will be generated in the "main" method.
for (int i = 0; i < employeeNumber; i++) {
if (!arrayList.contains(employee.getSurname())) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
} // WHY?
}
public String fire(Employee employee) {
for (Employee i : arrayList) {
if (employee.getSurname().equals(i.getSurname())) {
arrayList.remove(employee);
return "Fired"; // returns nothing and terminates the method execution.
}
}
return "The person of the" + employee.getSurname() + " surname doesn't work in the company";
}
}
public abstract class Employee {
private String surname;
private float contract; // contract = workperiod
public String getSurname() { // Here we're asking about a surname of an employee
return surname;
}
public float getContract() {
return contract;
}
public Employee(String surname, float contract) {
this.surname = surname;
this.contract = contract;
}
public abstract float pay();
public abstract String group();
}
Change String hire(Employee employee.getSurname()) to String hire(Employee employee).
Edit:
About the Employee that you want to hire() by surname (which I've explained you why this is a bad idea) do this:
public String hire(Employee employee) {
for (int i = 0; i < arrayList.size(); i++) { // you had employeeNumber instead of arraylist.size() but hire() method does not know anything about that variable
Employee temp = arraylist.get(i);
if (temp.getSurname().equals(employee.getSurname)) {
arrayList.add(employee);
return "Hired"; // "return" terminates the execution of the method.
}
}
}

Adding values to the objects without looping

I want to add values to the objects with out looping because if there are 1000 of objects then I don't want to loop all of them.I want to add age randomly to the students based on the Name of the student.Is there are any way to add values
Here is the code
import java.util.*;
import java.io.*;
class Student{
Student(String Name){
this.Name=Name;
}
String Name;
int age;
}
public class HelloWorld{
public static void main(String []args){
String a []={"Ram","Krishna","Sam","Tom"};
ArrayList<Student> al = new ArrayList<Student>();
for(int i=0;i<a.length;i++){
Student c;
c=new Student(a[i]);
al.add(c);
}
for(Student obj:al){
if(obj.Name.equals("Krishna")){
obj.age=24;
}
System.out.println("Name = "+ obj.Name + " Age = " + obj.age);
}
}
}
First some minor points:
You should never use the fields directly but create getter and setters instead. The fields should be private. Variable names should start with a lower case letter by convention. So this would be the adjusted Student class:
public class Student {
private String name;
private int age;
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
To store the Student objects you can use a map with names as keys and Student instances as values.
It is good practice to declare the variable only with the interface type Map and not with the concrete implementation HashMap. A hash map has O(1) complexity for searching by key. So you don't need a loop to iterate through all Student instances. (The HashMap.get() implementation doesn't use a loop internally.)
public static void main(String[] args) {
String a [] = {"Ram", "Krishna", "Sam", "Tom"};
// Keys: student names
Map<String, Student> al = new HashMap<String, Student>();
// Fill the Student's map
for(int i = 0; i < a.length; i++){
String name = a[i];
al.put(name, new Student(name));
}
// Manipulate one student by name. If there is no entry for that name we get null.
// So we better check for null before using it.
Student student = al.get("Krishna");
if(student != null) {
student.setAge(24);
}
// Output the all students
for(Student obj: al.values()){
System.out.println("Name = "+ obj.getName() + " Age = " + obj.getAge());
}
}

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

Print array variables, not variable pointer locations [duplicate]

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.

Generics: java.lang.String cannot be applied to Student

I am in class and my professor is saying her code works and there is nothing wrong with it and that it must be me. I have looked over her code and copied it word for word like she stated however I am still receiving the error:
Pair.java:28: set(java.lang.String,java.lang.Double) in Pair cannot be applied to (Student,java.lang.Double)
The part I bolded is the part I receive an error on. Are the set methods incorrect? Because the line with the error goes back to the set methods
This is her code:
Student.java
import java.io.*;
public class Student implements Person {
String id;
String name;
int age;
//constructor
public Student(String i, String n, int a) {
id = i;
name = n;
age = a;
}
public String getID() {
return id;
}
public String getName() {
return name; //from Person interface
}
public int getAge() {
return age; //from Person interface
}
public void setid(String i) {
this.id = i;
}
public void setName(String n) {
this.name = n;
}
public void setAge(int a) {
this.age = a;
}
public boolean equalTo(Person other) {
Student otherStudent = (Student) other;
//cast Person to Student
return (id.equals(otherStudent.getID()));
}
public String toString() {
return "Student(ID: " + id +
",Name: " + name +
", Age: " + age +")";
}
}
Person.java
import java.io.*;
public interface Person {
//is this the same person?
public boolean equalTo (Person other);
//get this persons name
public String getName();
//get this persons age
public int getAge();
}
Pair.java
import java.io.*;
public class Pair<K, V> {
K key;
V value;
public void set (K k, V v) {
key = k;
value = v;
}
public K getKey() {return key;}
public V getValue() {return value;}
public String toString() {
return "[" + getKey() + "," + getValue() + "]";
}
public static void main (String [] args) {
Pair<String,Integer> pair1 =
new Pair<String,Integer>();
pair1.set(new String("height"),new
Integer(36));
System.out.println(pair1);
Pair<String,Double> pair2 =
new Pair<String,Double>();
//class Student defined earlier
**pair2.set(new Student("s0111","Ann",19),**
new Double(8.5));
System.out.println(pair2);
}
}
For the instantiation:
Pair<String,Double> pair2 = new Pair<String,Double>();
your set() method signature is equivalent to: set(String, Double). And you are passing it a Student reference in the below invocation, which wouldn't work, as Student is not a String.
pair2.set(new Student("s0111","Ann",19), new Double(8.5));
To avoid the issue, change the declaration of pair2 to:
Pair<Student,Double> pair2 = new Pair<Student,Double>();
The error is pretty self explanatory. pair2 is defined as a Pair<String, Double>. You're trying to set a Student, Double. That won't work.
Pair<String,Double> pair2 = new Pair<String,Double>();
should be:
Pair<Student,Double> pair2 = new Pair<Student,Double>();
from your code pair2 is defined as type Pair<String,Double>,i.e pair2 set() method expecting String ,Double as arguments,but you are passing Student , Double.
So
Pair<String,Double> pair2 = new Pair<String,Double>();
should be
Pair<Student,Double> pair2 = new Pair<Student,Double>();

Categories