Change the name of a class object Java, use class as array - java

Here are my instructions:
Class Person
has instance data members (all private) String fullName, char gender, int age.
has a public static int variable named numFriends with an initial value of zero.
has a constructor that will be used to make a Person object and assign values to its data members, and increment numFriends.
has getters and setters for all three instance data members.
has a toString() method that returns a string displaying the state of a Person instance.
Class TestPerson
This class needs a main method and two more methods. In main, create three Person instances and display their status. Then call the void changeName method (see below) to change the name of one of the Person objects. Next, create an array of Person objects that holds the three instances created earlier. Then, call the agePersons method with this array and an integer as arguments. The agePersons method is described below. It returns an array with all Person objects aged by the value of the yrs argument. Use a loop to process and display the status of the elements in the array returned by agePersons. Finally, display the value of the static numFriends attribute.
public static void changeName(Person p) {
}
this method should be used to change the name of the Person passed to it as an argument. See sample output.
public static Person[ ] agePersons(Person[ ] ara, int yrs) {
}
this method takes a Person array and an integer (for years) as arguments, and adds that many years to the age of every Person in the array. The modified array is then returned.
SAMPLE OUTPUT
Three people at first
Person fullName=Otto Mattik, gender=M, age=22
Person fullName=Anna Bollick, gender=F, age=19
Person fullName=Dick Tator, gender=M, age=33
Three persons after 5 years
Person fullName=Otto Mattik, gender=M, age=27
Person fullName=Anna Bollick-Mattik, gender=F, age=24
Person fullName=Dick Tator, gender=M, age=38
We created 3 Person objects.
So far here is my code:
class Person {
private String fullName;
private char gender;
private int age;
public static int numFriends = 0;
public void setName(String nm) {
fullName = nm;
}
public void setAge(int a) {
age = a;
}
public void setGender(char g) {
gender = g;
}
public String toString() {
return (fullName + " gender is " + gender + " age is " + age );
}
}
And here is the second code file:
public class PersonTest {
public static void changeName(Person p, String nm) {
p.setName(nm);
}
public static Person[ ] agePersons(Person[ ] ara, int yrs) {
}
public static void main(String[] args) {
System.out.println("Three People At First:");
Person p1 = new Person(); // create Person
p1.setAge(22);
p1.setName("Otto Mattik");
p1.setGender('M');
Person p2 = new Person(); // create Person
p2.setAge(19);
p2.setName("Anna Bollick");
p2.setGender('F');
Person p3 = new Person(); // create Person
p3.setAge(38);
p3.setName("Dick Tator");
p3.setGender('M');
changeName(p2, "Anna Bollik-Mattik");
System.out.println(p1.toString());
System.out.println(p2.toString());
System.out.println(p3.toString());
}
}
And this is my output:
Three People At First:
Otto Mattik gender is M age is 22
Anna Bollick-Mattik gender is F age is 19
Dick Tator gender is M age is 38
I'm having a tough time figuring out how to set up my array with the objects that were already created and getting the age to increase across the board.

You're going to have to iterate through all the Persons in the array
public static Person[ ] agePersons(Person[ ] ara, int yrs) {
Person[] newArray = new Person[ara.length];
for (int i = 0; i < ara.length; i++){
newArray[i] = ara[i];
newArray[i].setAge(newArray[i].getAge() + yrs);
}
return newArray;
}

Related

Why can't I access the Object's properties from another class? (even when the Object was passed to the class that is trying to access the properties)

I hope you are able to help me.
My question is:
When passing an instance of an object that is in an arraylist, and I pass that arraylist to another class, how do I access it's atributes?
I can access the attributes before passing it to another class.
The "Main" class, passes on the data, to the "Employees" class.
Employees employees = new Employees();
employees.addEmployee("Orlando", "Silva", 111111111, "St. King's Street", 111111111, 11111111111111L, employees.getMinimumWage(), employees.getDayShift());
employees.addEmployee("Rui", "Guilherme", 111111111, "St. King's Street", 111111111, 11111111111111L, employees.getMinimumWage(), employees.getNightShift());
employees.addEmployee("Marco", "Alberto", 111111111, "St. King's Street", 111111111, 11111111111111L, employees.getMinimumWage(), employees.getNightShift());
The "Employees" class receives the data, adds it to an array, and from that array goes to the "AllStaff" class
Notice, that I have access to the atributes, in the method "addToAllStaff()"
public class Employees {
// Atributes
public String name;
private String lName;
private int nID;
private String address;
private int phNum;
private long nSocialSecNum;
private double minimumWage = 740.83;
private double employeeWage;
private String dayShift = "Day shift", afternoonShift = "Afternoon shift", nightShift = "Night shift";
private String shift;
private ArrayList<Employees> employeesArrayList = new ArrayList<Employees>();
private AllStaff allStaff = new AllStaff();
//---------------------
// Constructors
public Employees(){
}
public Employees(String name, String lName, int nID, String address, int phNum, long nSocialSecNum, double minimumWage, String shift){
this.name = name;
this.lName = lName;
this.nID = nID;
this.address = address;
this.phNum = phNum;
this.nSocialSecNum = nSocialSecNum;
this.employeeWage = minimumWage;
this.shift = shift;
//----------------
extraWage();
}
//---------------------
public void addEmployee(String name, String lName, int nID, String address, int phNum, long nSocialSecNum, double minimumWage, String shift){
Employees employee = new Employees(name, lName, nID, address, phNum, nSocialSecNum, minimumWage, shift);
employeesArrayList.add(employee);
addToAllStaff();
}
void addToAllStaff(){
System.out.println("(Class Employees) employees size: " + employeesArrayList.size());
for (int i = 0; i < employeesArrayList.size(); i++){
System.out.println("Employee names: " + employeesArrayList.get(i).getName());
System.out.println("Employee names: " + employeesArrayList.get(i).name);
}
allStaff.addEmployees(employeesArrayList);
}
}
In the class "AllStaff", is where I don't have access to the attributes
public class AllStaff {
static ArrayList <AllStaff> employeesArrayList;
public AllStaff(){
}
public void addEmployees(ArrayList listOfEmployees){
System.out.println("List of employees size: " + listOfEmployees.size());
for (int i = 0; i < listOfEmployees.size(); i++){
System.out.println("Employee names: " + listOfEmployees.get(i).getName());
System.out.println("Employee names: " + listOfEmployees.get(i).name);
}
this.employeesArrayList = listOfEmployees;
}
For the whole code, please visit this link: https://github.com/OrlandoVSilva/test-to-github/tree/master/test-to-github/src/mercado
I hope this question has everything you need.
Thanks
When using a List (or any object that can be generic), it's a good practice to specify the type of List you're dealing with. In your case, the method addEmployees(ArrayList listOfEmployees) takes in parameter an ArrayList, which could be an ArrayList of literally any object. It could be an ArrayList of Employees, Strings, Integers, whereas you just want it to be an ArrayList of Employees.
the solution is to change your ArrayList into a ArrayList<Employees> listOfEmployees
public void addEmployees(ArrayList<Employees> listOfEmployees){
System.out.println("List of employees size: " + listOfEmployees.size());
for (int i = 0; i < listOfEmployees.size(); i++){
System.out.println("Employee names: " + listOfEmployees.get(i).getName());
//The above should work just fine :)
System.out.println("Employee names: " + listOfEmployees.get(i).name);
//This one will work too as the "name" attribute is public but as you have a getName() method, you probably should make it private :D.
}
this.employeesArrayList = listOfEmployees;
}
To explain it quickly without too much details, when you're using a List object, you must specify the List's type by putting <> around it. If you don't, the default type is Object which is the parent of every types in java.
Also, i guess your static ArrayList <AllStaff> employeesArrayList; is meant to be your list of employees. So replacing it with static ArrayList <Employees> employeesArrayList; seems to be what you want to do :D
You missed generics type in AllStuffs addEmployees() method argument. That is the problem. It should be like this:
public void addEmployees(ArrayList<Employees> listOfEmployees){

Why do I get null as my output string instead of what I wanted?

I'm asked to compute a Java program with TestStaff that accepts name,
staff id and working perday as inputs from the user and displays the name, staff ID and salary of the staff. But at the end of the output, I got null null 0.0 . I'm a beginner at this object and class section and I'm really lost. Can anyone help? Here are my codes:
This is the given code:
class Staff {
private String name, staffID;
private double salary;
private int workingDay;
public void setStaffInfo(String nm, String id, int wDay){
name=nm;
staffID=id;
workingDay=wDay;
}
public void calculateSalary(){
salary = workingDay * 35.0;
}
public double getSalary(){
return salary;
}
public String getName(){
return name;
}
public String getStaffID(){
return staffID;
}
}
import java.util.Scanner;
Here are the codes for TestStaff:
class TestStaff {
static Scanner console = new Scanner(System.in);
public static void main(String arg[]){
Staff staff1= new Staff();
System.out.print("Enter your name: ");
String nm=console.nextLine();
System.out.print("Enter your Staff ID: ");
String id=console.nextLine();
System.out.print("Enter your working days: ");
int wDay=console.nextInt();
System.out.println(staff1.getName() + "\t" + staff1.getStaffID()+ "\t\t" + staff1.getSalary());
}
}
You need to use the Staff class set method to initialize its members.
i.e: staff1.setStaffInfo(nm, id, wDay);
What you've done is simply creating 3 new variables and assigning them values, but your Staff objects' members were not set.
Also you might want to call calculateSalary() before getSalary() because the former initializes the salary variable.
You are missing to call method staff1.setStaffInfo(nm, id, wDay);
I would suggest to have parameterized constructor with all the instance variables of class Staff, create instance for Staff using that constructor. That way you won't get null values.
Suggestion:
Create constructor in Staff class as:
Staff(){}
Staff(String name, String staffID, double salary , int workingDay){
this.name = name;
this.staffID=staffID;
this.salary=salary;
this.workingDay = workingDay;
}
And in TestStaff class, you can add these lines:
Staff staff2 = new Staff(nm,id, 2400, wDay);
System.out.println(staff2.getName() + "\t" + staff2.getStaffID() + "\t\t" + staff2.getSalary());
In the main method you have created the Staff object and stored all the input in some variable but haven't set the input in object. Thats why when you print staff1.getSalary() it returns you the default value of double i.e: 0.0. first set the value staff1.setInfo(...) And then print the values.
But at the end of the output, I got null, null, 0.0.
You are not passing any arguments to the setStaffInfo(String nm, String id, int wDay) anywhere in your code so that is why it is showing null, null,0.0
Solution
Pass the following variables to the setStaffInfo(String nm, String id, int wDay) method of the class Staff
String nm=console.nextLine();
String id=console.nextLine();
int wDay=console.nextInt();
Like this:
staff1. setStaffInfo(nm,id,wDay)
And an advice
Run your calculateSalary() in getSalary() method like this:
public double getSalary(){
calculateSalary(); //this will autimatically calculate salary
return salary;
}
Then, you will just have to call getSalary() in the main method and it will automatically call calculateSalary() or you can also put that one line of calculateSalary()in getSalary() also.
You create a new object from your Class Staff but you have to assign data member to the class and can done from 2 different ways :
1- Your method staff1.setStaffInfo(nm, id, wDay);
staff1.setStaffInfo(nm, id, wDay);
2- Constructor
Staff staff1= new Staff(id, nm, wDay);
Add the constructor below in Staff class this constructor will make you able to create a new object with specifying id, nm and wDay
Staff (String staffID ,String name , int workingDay) {
this.staffID = staffID;
this.name = name ;
this.workingDay = workingDay ;
}

How to add a specific number of objects based on user input in a TreeSet?

I am doing the question below:
A university wishes to keep student records in such a way that there are no
duplicate student record for any student. Student details are as follows: national
ID card number, surname, first name, address and programme of study.
i. Write a class named Student which will allow the creation of objects with
the above-mentioned attributes. Only the implementation of the
constructor is required.
ii. Amend the class above to make all the Student objects orderable based
on their surname, in case two students have the same surname, their Id
card number will be used to order them.
iii. Write code to declare a suitable data structure to store the records
iv. Write code to add a student object, S1, to the list.
v. Write code to ask the user for an integer, n, and then allows insertion of n
Students objects in the data structure.
vi. Write code to display all the details of all the Student objects from the data
structure.
Here is what I have come up with so far:
import java.util.Comparator;
import java.util.Scanner;
import java.util.SortedSet;
import java.util.TreeSet;
public class Student {
private String nID;
private String lname;
private String fname;
private String address;
private String pos;
public Student(String nID, String lname, String fname, String address, String pos){
this.nID=nID;
this.lname=lname;
this.fname=fname;
this.address=address;
this.pos=pos;
}
public Student() {
// TODO Auto-generated constructor stub
}
final static Comparator<Student> nameComparator=new Comparator<Student>(){
public int compare(Student A, Student B){
if((A.lname.compareTo((B.lname)))<0){
return -1;
}
else if(A.lname.compareTo(B.lname)>0){
return 1;
}
else{
return (A.nID.compareTo(B.nID));
}
}
};
public String toString(){
return "National ID: "+ nID+ " First Name: "+ fname+ " Last Name: "+ lname+ " Address: " +address+ " PoS"+pos+"\n";
}
public static void main(String[] args){
Scanner sc= new Scanner(System.in);
SortedSet<Student> names= new TreeSet<Student>(nameComparator);
int num;
System.out.println("Enter the number of students");
num=sc.nextInt();
Student a = new Student("daaa", "Jam", "Jick", "iiii", "ooooo");
Student b = new Student("bba", "Aarav", "Gash", "iiii", "pooo");
Student c = new Student("ccaa", "Jam", "Kick", "iiii", "ooooo");
names.add(a);
names.add(b);
names.add(c);
for(int i=0; i<num; i++){
names.add(new Student());
}
for(Student i: names){
System.out.println(i.toString());
}
}
}
I am not sure of how to do the 5th part of the question or if I understood it well.
When I execute this program I get null point exception at the name comparison and the add method in the for loop. I know the null pointer exception is because I have not added any arguments in the student object names.add(new Student()); but I want to find the right way of doing it.
This
for(int i=0; i<num; i++){
names.add(new Student());
}
will always add Student having all "null" fields. Use your other constructor instead:
public Student(String nID, String lname, String fname, String address, String pos){

Link ArrayLists and save data on file

I am working on a Java app for a school project where we have to enter user information: Name, Student ID and their points. How can I store all the data for each user on an ArrayList (or an Array or really whatever type) so I can keep track of all the data.
Example:
John Doe - 401712 - 20 points
Jack Young - 664611 - 30 points
The I want to be able to call methods like setPoints to change the point values for whatever the student selected is.
Here's the problem: How can I link the ArrayList together. If I have three ArrayLists, how does Java know what name, student id and points are associated together?
All the ArrayLists are stored in a class called Data.
Data data = new Data();
Also, all the ArrayLists in the Data class should be outputted to a file which will be loaded next time the app is opened.
I will try to answer any questions.
You need to define a class which contain 3 data fields as follows
Name
Student ID
their points
But not to forget, the class has to have other necessary elements of a class like:
Constructor
Overloaded Constructors if they are necessary
Accessors
Mutators
Note: For accessing each part of an object in your arrayList, you can use accessors. For manipulating each part of an object in your arrayList, you can use mustators.
After having such a class, you can define a arrayList that contain elements with type of class you have already define
Like:
List<Your Type of class > students = new ArrayList<Your Type of class>;
After Java 7, you can do
List<Your Type of class > students = new ArrayList<>;
which is diamond inference.
If you are looking for a specific id number in your arrayList, you can do something like:
public boolean findIdNumber(int idNumber){
for(int i=0; i< students.size; i++)
if(students.get(i).getID() == idNumber)
return true;
else
return false;
}
Warning:
what I have done are suggestions for you to be able to look for what you want smoother. You need to do necessary changes in order to comply what you were
asked to do
You need to create a class named Student, and then declare an array/ArrayList of the Student type. Your Student class must have a constructor that sets the fields of an instance of the Student class (the created instance is now called an object).
So first create a Student class in the same package in which your other class is (the class in which your main method is):
public class Student {
private String firstName;
private String lastName;
private String studentId;
private int points;
public Student(String firstName, String lastName, String studentId, int points) {
this.firstName = firstName;
this.lastName = lastName;
this.studentId = studentId;
this.points = points;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
}
Then in your main method or wherever you like, create a Hashmap to hold your Student objects. A map/hashmap is a collection just like an ArrayList to hold a set of objects. In your use case, it is better to use a hashmap because finding/retrieving a specific student object is much faster and easier when you use a hashmap.
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
// a map is a "key-value" store which helps you search items quickly
// (by only one lookup)
// here you consider a unique value of each object as its 'key' in the map,
// and you store the whole object as the value for that key.
// that is why we defined Student as the second type in the following
// HashMap, it is the type of the "value" we are going to store
// in each entry of this map.
Map<String, Student> students = new HashMap<String, Student>();
Student john = new Student("John", "Doe", "401712", 20);
Student jack = new Student("Jack", "Young", "664611", 30);
students.put("401712", john);
students.put("664611", jack);
Student johnRetrieved = students.get("401712");
// each hashmap has a get() method that retrieves the object with this
// specific "key".
// The following line retrieves the student object with the key "664611".
Student jackRetrieved = students.get("664611");
// set/overwrite the points "field" of this specific student "object" to 40
johnRetrieved.setPoints(40);
int johnsPoints = johnRetrieved.getPoints();
// the value of johnsPoints "local variable" should now be 40
}
}
The classical object-oriented approach would be to create a Student class including name, ID and points and storing list of Student objects in a single ArrayList.
class Student{
private String id;
private String name;
private int points;
public Student(String id, String, name, int points){
this.id = id;
this.name = name;
this.points = points;
}
}
..
ArrayList<Student> students = new ArrayList<Student>();
students.add(new Student(1, 'John Doe', 1000));
String id = students.get(0).id;

How to use an object without knowing the objects' name

I'm not too sure how to word this so it makes sense, but I'll try my best.
Say I have 2 classes. My main class, and a Person class.
My main class will create some Objects from the Person class like this
public class Example {
static Person bob = new Person(23);//Age
static Person fred = new Person(34);
static Person John = new Person(28);
//..and so on
public static void main(String args[]){
..
}
}
and in my Person class..
public class Person{
private int age;
public Person(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
Now, if I wanted the age of fred, I'd just call Fred.getAge();.
But, in my program, I don't know what person I'm getting the age of. It randomly selects one, and I need to get the name without directly calling the object. For example, I would have something like this in my Person class:
public static Object getPerson(){
//Some code to get a random integer value and store it it Var
switch(Var){
case 1:
return bob;
case 2:
return fred;
case 3:
return john;
}
}
What I would expect this to do is return an Object that I could then use like this:
public static void main(String args[]){
System.out.println(Person.getPerson().getAge());
}
What I thought that would have done was first call getPerson() which randomly returns either bob, fred, or john, and then it would call getAge(). So if getPerson() returned fred then it would be the same as doing fred.getAge();
Now, this doesnt work, and this was the only way I thought of that made sense to me.
How do I do this so it actually does what I want?
I'm very new to Java, and OOP, and this is my first time really working with different Objects. So I'm sorry if I'm using the wrong terms and explaining things weirdly.
Change
public static Object getPerson(){
to
public static Person getPerson(){
You can't call getAge on an Object, because the Object type does not have getAge() defined.
Why not put the name as a property of the Person class?
class Person {
// ... your existing code for age...
private String name;
String getName() { return name; }
// add name to constructor...
public Person(String name, int age) {
// set them up here...
}
}
The way I see it, is that name is for you as a human, but variables john are irrelivant to the program and computer.... you can even use p1 = Person("Joe", 42);
To get a person by age, you can use a Map with age as key, and person as value.
It could be the case that this is a misunderstanding, but how I'm interpreting the issue is as follows:
You need a (better) place to store all of your Person objects instead of having them as static variables.
You need a way to randomly select from wherever you're storing those objects.
Let's address the main issue first. You're creating these as static variables when they probably shouldn't be; they should just be created as entries into an array.
The way to do this is through this declaration:
Person[] people = new Person[] {new Person(23), new Person(34), new Person(28)};
The main issue now is that you have no way to refer to which person's age belongs to whom since you haven't attached a name field to any of these instances. You could do that easily:
public class Person {
private String name;
private String age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters for name and age
}
...then you can instantiate your Person with two values.
new Person("Bob", 23);
Now that we've addressed one concern (which was where to store the people in the first place), now we need a way to randomly access them.
For that, we can use Random#nextInt().
Random rand = new Random();
System.out.println("Person's age - " + people[rand.nextInt(people.length)]);
This will randomly pull a Person out of the array and print their age.
If you want to get a random person within the person class you could store a reference to each person created, and then select randomly from that list
public class Person {
// A List of every Person Created.
private static final List<Person> allPeople = new ArrayList<People>();
// A source of random numbers
private static final Random rand = new Random();
...
public Person(int age) {
...
// Every time we create a new Person, store a reference to that person.
addPerson(this);
}
// synchronized as ArrayLists are not thread safe.
private static synchronized addPerson(Person person) {
allPeople.add(person);
}
...
public static Person getRandomPerson() {
// Get a random number between zero and the size of the list.
int random = rand.nextInt(allPeople.size() -1);
return allPeople.get(random);
}
Now this code is not what I would do in a production environment but it the question sounds like an exercise. A better way would be to store the people created in a List in your Example class. But trying to answer the question as you asked it.

Categories

Resources