java : Parsing An ArrayList and setting them into a Object - java

I have these two classes:
class Student
{
String name;
String age ;
}
class Person
{
String name;
String age ;
String grade ;
}
In the code below, I am creating Student objects and setting them inside the ArrayList. Once the data is set in the ArrayList, I need to parse that ArrayList and set the values in another object:
public class Work {
public static void main(String args[]) {
List StudentItems = new ArrayList();
Student stud1 = new Student();
Student stud2 = new Student();
stud1.name = "ABC";
stud1.age = "28";
stud2.name = "XYZ";
stud2.age = "38";
StudentItems.add(stud1);
StudentItems.add(stud2);
Person[] pers = new Person[StudentItems.size()];
for (int i = 0; i < StudentItems.size(); i++) {
pers[i] = new Person();
// I am confused here , could anyone please help
}
}
}

Try it out. This will do the work
Your Person class should be something like this:
package com.student.person.work;
/**
*
* #author sarath_sivan
*/
public class Person {
private String name;
private int age;
private String grade;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
public String getGrade() {
return this.grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
Your Student class should be something like this:
package com.student.person.work;
/**
*
* #author sarath_sivan
*/
public class Student {
private String name;
private int age;
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return this.age;
}
public void setAge(int age) {
this.age = age;
}
}
And finally, the Work class:
package com.student.person.work;
import java.util.ArrayList;
import java.util.List;
/**
*
* #author sarath_sivan
*/
public class Work {
public static String calculateGrade() {
String grade = "";
// Your code to find the grade.
//............
return grade;
}
public static void doWork() {
List<Student> studentList = new ArrayList<Student>();
Student student = new Student();
student.setName("ABC");
student.setAge(24);
studentList.add(student);
student = new Student();
student.setName("DEF");
student.setAge(28);
studentList.add(student);
student = new Student();
student.setName("GHI");
student.setAge(21);
studentList.add(student);
List<Person> personList = new ArrayList<Person>();
for(Student students : studentList) {
Person person = new Person();
person.setName(students.getName());
person.setAge(students.getAge());
person.setGrade(Work.calculateGrade());// Setting the grade
}
}
public static void main(String[] args) {
Work.doWork();
}
}
Hope this will be helpful.
Thank you!

Something like this:
List<Student> studentItems = new ArrayList<Student>();
Student stud1 = new Student();
Student stud2 = new Student();
stud1.name = "ABC";
stud1.age = "28";
stud2.name = "XYZ";
stud2.age = "38";
studentItems.add(stud1);
studentItems.add(stud2);
for (int i = 0; i < studentItems.size(); i++) {
Student student = studentItems.get(i);
Person person = new Person();
person.name = student.name;
person.age = student.age;
// person.grade = something - set grade here
pers[i] = person;
}
But be avare that you shouldn't use public fields... so it should look like this:
for (int i = 0; i < studentItems.size(); i++) {
Student student = studentItems.get(i);
Person person = new Person();
person.setName(student.getName());
person.setAge(student.getAge());
// person.setGrade(computeGradeSomehow()); - set grade here
persons[i] = person;
}

If you are frequently converting from student object to Person object, add following like constructor and setter/getter method
class Person {
String name;
String age;
String grade;
public Person() {
}
Person(Student student) {
this.name = student.getName();
this.age = student.getAge();
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
class Student {
private String name;
private String age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
And in Work class, create Person object like,
List<Student> studentItems = new ArrayList<Student>();
List<Person> personItems = new ArrayList<Person>();
for (int i = 0; i < studentItems.size(); i++) {
Student student = studentItems.get(i);
Person person = new Person(student);
person.setGrade(your_formula_for grade);
personItems.add(person);
}

You can do it as follow:
pers[i].name = StudentItems.get(i).name;

Grade should be in the Student class. If you to this, your classes should look like this:
class Person {
private String name;
private int age;
//getters and setters
}
class Student extends Person { // here you have name and age from Person
private String grade;
//getters and setters
}
Now, you want the list of persons from the list of students? You can do this:
for (int i = 0; i < listOfStudents.size(); i++){
arrayOfPersons[i] = (Person)listOfStudents.get(i);
}

Given, that your classes are really properly layouted (see my comment), you could write a constructor for person which takes an Student as input:
pers[i] = new Person (StudentItems[i]);
note, that I would rename the variables:
persons [i] = new Person (students[i]);
Your Person with the new CTor would look like this:
class Person
{
String name;
String age ;
String grade ;
public Person () {}
public Person (s Student) {
name = s.name;
age = s.age;
}
}
More probably, you want to change the name of Student and Person, and derive Student from Person. Then, every Student is a person, and in your loop, it is justs:
persons [i] = students[i];

Related

Generate an ID for each object in java [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 1 year ago.
I have an array in the main class which holds Employee class objects. I'm trying to generate a unique ID for each object but it is printing the same ID for all the objects
Main class:
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
Employee class
public class Employee {
private String name;
private int age;
private static String employeeID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
public String getName() {
return name;
}
public String setName(String name) {
this.name =name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(employeeID);
++id;
return Integer.toString(id);
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
I want the employeeID as string and I can't use java.util.UUID; for my project.
You need a static variable associated with the class to maintain the unique id and an instance variable to keep that particular employee's ID in the class.
private String employeeID; // instance member
private static String uniqueID = "0"; // static class variable
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID); // get the static variable
++id; // increment it
uniqueID = Integer.toString(id); // update the static variable
return uniqueID; // return the value to use for the employee
}
Then in the Employee constructor, use the static member:
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
updated Employee class:
public class Employee {
private String name;
private int age;
private String employeeID;
private static String uniqueID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
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;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID);
++id;
uniqueID = Integer.toString(id);
return uniqueID;
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
Output:
Luke 36 1
Martin 49 2
Kevin 21 3
Sam 43 4
Nicole 45 5
Linta 21 6
You should store last generated id in static field but use non static for id of certain employee.
Also you should use AtomicInteger type for thread safety which you can convert to String. Check that:
import java.util.concurrent.atomic.AtomicInteger;
public class Employee {
private String employeeID;
private String name;
private int age;
private static AtomicInteger lastGeneratedId = new AtomicInteger(0);
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
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;
}
public static String getNextUniqueID() {
return String.valueOf(lastGeneratedId.incrementAndGet());
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
}

Get object's attribute into java for each loop

public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age= age;
}
Person Rome[] = new Person[10];
public void initializes {
Rome[0]= new Person ("Antonio",20);
Rome[1]= new Person ("Marco",11);
//...
Rome[9]= new Person("Giuseppe",27);
}
public void printName(){
for(Person x : Rome){
System.out.println(x.name);
}
}
//TEST CLASS
public static void main (String args[]){
Person obj = new Person();
obj.initializes();
obj.printName(); // Exception in thread "main" java.lang.NullPointerException
}
}
why the print of for each work just with primitive object , if i want print a attribute of complex object not work why?
You need to initialize Rome[0] object.
It will be look like:
public void initializes {
Rome[0]= new Person ("name",00);
Rome[1]= new Person ("Antonio",20);
//...
}
And code will be better if you'll initialize your object without object class. In test class for example:
Person[] Romeo = new Person[] {
new Person(name, 00),
//...
}
And the result:
the file name Test.java
//and there is the code. it is prototype and I did'n compile it, but it is an example for you
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age= age;
}
public void printName(){
System.out.println(name);
}
}
//Test class
public class Test {
public static void main (String args[]){
Person[] Romeo = new Person[] {
new Person("name", 00),
//...
}
for(int i = 0; i < 10; i++)//or another loop style
Romeo[i].printName();
}
}

Adding objects of a class to an ArrayList in another class

Im trying to add Objects of a Class called Student to an Arraylist in another class called StudentClass. I have initialised the list, but am having trouble working out how to add objects to the ArrayList
Code for StudentClass
public class StudentClass
{
List<Student> studentList;
private String studentName;
private int lengthOfString;
public StudentClass()
{
super();
studentList = new ArrayList<>();
}
public void addStudent(String aName)
{
String objt = new String(name, mark);
studentList.add(Student);
}
Code for Student
public class Student
{
private String name;
private int mark;
public Student(String aName)
{
super();
this.name = aName;
this.mark = -1;
Try this:
public void addStudent(String aName) {
studentList.add(new String(aName));
}
Also, Student class constructor does not accept marks as second parameter, at least the code what you have posted.
This should work.
import java.util.*;
public class StudentClass
{
List<Student> studentList;
private String studentName;
private int lengthOfString;
public StudentClass()
{
super();
studentList = new ArrayList<>();
}
public void addStudent(String aName) {
Student student = new Student(aName);
studentList.add(student);
}
}
public class Student
{
private String name;
private int mark;
public Student(String aName)
{
super();
this.name = aName;
this.mark = -1;
}
}
I'm not clear what you're trying to do with the mark?
Seems that your mistake is here:
String objt = new String(name, mark);
studentList.add(Student);
Write this instead:
Student objt = new Student(name, mark);
studentList.add(objt);
You need to create a new Student object and then add that to your list:
public void addStudent(String aName) {
Student student = new Student(aName);
studentList.add(student);
}
It's not really clear from your provided code how the mark field is set, but either pass it through the Student construction and/or add getters and setters.

Java: how to return an Array?

this is the code, from what I understand, it is suppose to work.
Also when I debug my program, it seems that the array is being filled with the objects that the same method is creating.
But still, when I try to print it, it shows me "null" back agian, like the "return" does not work.
Why is it happening?
public class Course {
String courseName;
String teacherName;
int gradeAv;
static int counter;
static int maxNumOfStudents;
Student studentsArray[] = new Student[5];
int numOfStudents = studentsArray.length;
public Course() {
}
public Course(String courseName) {
this();
this.courseName = courseName;
}
public Course(String courseName, String teacherName) {
this(courseName);
this.courseName = courseName;
this.teacherName = teacherName;
}
public Student[] addStudent(String name, int age, int grade) {
for (int i = 0; i < 5; i++) {
studentsArray[i] = new Student(name, age, grade);
age += 10;
grade += 10;
}
return studentsArray;
}
public void printStudentArray(Student studentArray[]) {
studentArray = this.studentsArray;
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i]);
}
}
public int gradeAv() {
for (int i = 0; i < studentsArray.length; i++) {
int temp = 0;
if (studentsArray[i].grade > temp) {
gradeAv = temp;
System.out.println(gradeAv);
}
}
return gradeAv;
}
public void printCourse() {
System.out.println("Course: ");
System.out.println("Course Name: " + courseName + ". "
+ "Teacher's Name: " + teacherName + ". "
+ "Number Of Students: " + numOfStudents + ". ");
}
}
This is my main class:
public class MainClass {
public static void main(String[] args) {
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.printStudent();
System.out.println();
stud.printCourse();
System.out.println();
cour.printStudentArray(cour.studentsArray);
System.out.println();
// cour.gradeAv();
}
}
in
Student stud = new Student();
Course cour = new Course("Java", "Ronni");
stud.addStudent("Joe", 23, 100);
stud.addStudent("Joe", 23, 100); will not add any students to your course. stud is an instance of a completely different class, Student, and the implementation of Student is not in the code you've posted.
call the addStudent method of cour instead of the one for stud
cour.addStudent("Joe", 23, 100);
instead
I would also like to add that there are a lot of curious elements to your code, some of which people have brought up in the comments. It would be tedious to list them all. I'd take a look-through, just to make sure you're not doing redundant things.
Try this for example:
Course class:
import java.util.ArrayList;
import java.util.List;
public class Course {
private List<Student> students = new ArrayList<Student>();
private String teacherName;
private String subjectName;
public Course(String subjectName, String teacherName) {
this.subjectName = subjectName;
this.teacherName = teacherName;
}
public void addStudent(Student student) {
students.add(student);
}
public float getAverageGrade() {
float grade = 0;
for (Student student : students) {
grade += student.getGrade();
}
return grade / students.size();
}
public void printCourse() {
System.out.println("Course "+subjectName+" taught by "+teacherName);
System.out.println("Students:");
printStudents();
System.out.println("Aberage grade: "+getAverageGrade());
}
public void printStudents() {
for (Student student : students) {
System.out.println(student.getName()+"\t age "+student.getAge()+" \t grade "+student.getGrade());
}
}
}
Student class:
public class Student {
private String name;
private int age;
private int grade;
public Student(String name, int age, int grade) {
this.grade = grade;
this.age = age;
this.grade = grade;
}
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;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}

create new object in arraylist with attributes

I am new to Java and I am starting to work with ArrayLists. What I am trying to do is create an ArrayList for students. Each student has different attribute associated with them (name, id). I am trying to figure out how to add a new student object with this attributes. Here is what I have:
ArrayList < Student > studentArray;
public Student(String name, int id) {
this.fname = name;
this.stId = id;
}
public Stromg getName() {
return fname;
}
public int getId() {
return stId;
}
public boolean setName(String name) {
this.fname = name;
return true;
}
public boolean setIdNum(int id) {
this.stId = id;
return true;
}
What you need is something like the following:
import java.util.*;
class TestStudent
{
public static void main(String args[])
{
List<Student> StudentList= new ArrayList<Student>();
Student tempStudent = new Student();
tempStudent.setName("Rey");
tempStudent.setIdNum(619);
StudentList.add(tempStudent);
System.out.println(StudentList.get(0).getName()+", "+StudentList.get(0).getId());
}
}
class Student
{
private String fname;
private int stId;
public String getName()
{
return this.fname;
}
public int getId()
{
return this.stId;
}
public boolean setName(String name)
{
this.fname = name;
return true;
}
public boolean setIdNum(int id)
{
this.stId = id;
return true;
}
}
You instantiate a Student object by passing the appropriate values to the constructor.
Student s = new Student("Mr. Big", 31);
You place elements into an ArrayList (or List) by using the .add() operator.*
List<Student> studentList = new ArrayList<Student>();
studentList.add(s);
You retrieve user input via the use of a Scanner bound to System.in.
Scanner scan = new Scanner(System.in);
System.out.println("What is the student's name?");
String name = scan.nextLine();
System.out.println("What is their ID?");
int id = scan.nextInt();
You repeat this with a loop. That portion shall be left as an exercise to the reader.
*: There are other options, but add() simply adds it to the end, which is typically what you want.
final List<Student> students = new ArrayList<Student>();
students.add(new Student("Somename", 1));
... and so on add more students

Categories

Resources