Get object's attribute into java for each loop - java

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

Related

Calling an object arraylist from another class and iteration through it

I have a problem accessing the arraylist I created in a class. I tried going through the answers of questions similar to mine but unfortunately I was unable to solve the problem.
So I have two classes Student and Person and I want to iterate through the arraylist of Person in the class Student. (The code doesn't really make sense, I know. I just want to understand).
I tried two approaches :
1) creating a variable of type Person in Student class and calling the get method from person class.
2) creating a get method in the class person that returns arraylist.
Both are not working properly when i tried to call the isHere method in the main method.(false was printed instead of true)
I think my two approaches intialise a new array of type Person and not call the arraylist to which elements are already added. How can solve this?
import java.util.ArrayList;
public class Student {
private Person p;
private String name;
private int age;
private String address;
public Student() {
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public boolean isHere(String name) {
p = new Person();
// I also tried for(Person per : p.getList)
for (Person per : this.getL()) {
if (per.getName().equals(name)) {
System.out.println("hi");
return true;
}
}
return false;
}
public ArrayList<Person> getL() {
return p.getList();
}
public Person getP() {
return p;
}
public void setP(Person p) {
this.p = p;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
The Person class:
import java.util.ArrayList;
public class Person {
private String name;
private ArrayList<Person> list = new ArrayList<Person>();
Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ArrayList<Person> getList() {
return list;
}
public void setList(ArrayList<Person> list) {
this.list = list;
}
public void add(String name) {
list.add(new Person(name));
}
}
The statement p = new Person() in your isHere(..) method is creating a new Person object. When that Person object is created, the name in object p will be null and the list will be empty. So the for loop is never executed as the list is empty and hence it returns false.
If you ever want your code to run, you should not create the Person object and then immediately iterate through it because it will have nothing. You have to either add something to it or use a Person object which you believe will be populated before you run the isHere(..) method

Using Object class Reference variable, accessing different class members.

I am trying to access class members of different class i.e.,getDetails() from student as well as customer class using Object class Reference variable. But it looks like its not working. Please look into this easy code and help me out how to access the getDetails() using Object class ob[0] and ob[1]
class Customer
{
int custId;
String name;
Customer(String name, int custId)
{
this.custId = custId;
this.name = name;
}
public void getDetails()
{
System.out.println(this.custId+" : "+this.name);
}
}
class Student
{
int roll;
String name;
Student(String name, int roll)
{
this.name = name;
this.roll = roll;
}
public void getDetails()
{
System.out.println(this.roll+" : "+this.name);
}
public static void main(String []args)
{
Object[] ob = new Object[2];
ob[0] = new Student("Vishal", 041);
ob[1] = new Customer("Xyz" , 061);
ob[0].getDetails();
ob[1].getDetails();
}
}
Try creating a common interface that declares the method getDetails. Something like this:
public interface Person {
public void getDetails();
}
Let Student and Customer implement the interface. Then declare the array like this:
Person ent[] ob = new Person[2];
....

How to set / get a name to "ford" - instance of class Car I have created in main method of class Vehicle?

As you can see I am stuck in part where I should set a name an owner of ford... Thanks for help.
public class Vehicle {
Person owner;
long motorSerialNo;
String registerNo;
public static void main(String[] args) {
//an example, create an object instance of class Car
Car ford = new Car();
ford.model = "Focus";
ford.motorSerialNo = 123456;
ford.registerNo = "CA-126-65";
//and here is a problem
ford.owner.setName("John Croul");
}
}
class Car extends Vehicle {
String model;
}
class Person {
public Person(String name){
this.name = name;
}
String name;
String lastname;
String address;
String getName() {
return name;
}
void setName() {
this.name = name;
}
}
Firstly, your setter should look like
public void setName(String name) {
this.name = name;
}
Then you have to initialize the instance variable person before calling its method setName(), otherwise you will get the NullPoiterException.
Person owner = new Person();
or in the main method, as you did for other variables
ford.owner = new Person();

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 : Parsing An ArrayList and setting them into a Object

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

Categories

Resources