create new object in arraylist with attributes - java

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

Related

adding multiple objects to ArrayList is not printing very well

import java.util.ArrayList;
import java.util.Scanner;
public class Student {
static String studentNum;
static int age;
static String Name;
Student(int Age, String Name){
this.Name = Name;
this.age = Age;
}
public static String input_read() {
Scanner sc = new Scanner(System.in);
if (sc.hasNext()) {
studentNum = sc.next();
} else {
sc.close();
}
return studentNum;
}
public static int setAge() {
System.out.println("Enter the age of the Student");
return Integer.valueOf(input_read());
}
public static String setName() {
System.out.println("Enter the name of the Student");
return input_read();
}
public static int getAge() {
return age;
}
public static String getName() {
return Name;
}
public static void main(String[] args) {
ArrayList<Student> ar = new ArrayList();
for (int i=0; i<2; i++) {
Student s1= new Student(setAge(), setName());
ar.add(s1);
}
for (Student each :ar){
System.out.println(each.getName());
System.out.println(each.getAge());
}
}
}
I am new guy in Java. I created a program to add student age and name. This program output is printing only last object 2 times. It is not printing all the objects in the list. Anybody know why?
You should remove the keyword static from your member variables.
That is causing them to be shared across all instances.
See here: What does the 'static' keyword do in a class?

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.

Dynamically fill in an ArrayList with objects

I have the abstract class Human, which is extendet by other two classes Student and Worker. I`m am trying to fill in two array lists. ArrayList of type Student and ArrayList of type Worker dynamically.
public abstract class Human {
private String fName = null;
private String lName = null;
public String getfName() {
return fName;
}
public Human(String fName, String lName) {
super();
this.fName = fName;
this.lName = lName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
}
public class Student extends Human {
private String grade = null;
public Student(String fName, String lName, String grade) {
super(fName, lName);
this.grade = grade;
}
public String getGrade() {
return grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
public class Worker extends Human {
private int weekSalary = 0;
private int workHoursPerDay = 0;
public Worker(String fName, String lName, int weekSalary, int workHoursPerDay) {
super(fName, lName);
this.weekSalary = weekSalary;
this.workHoursPerDay = workHoursPerDay;
}
public int getWorkSalary() {
return weekSalary;
}
public void setWorkSalary(int workSalary) {
this.weekSalary = workSalary;
}
public int getWorkHoursPerDay() {
return workHoursPerDay;
}
public void setWorkHoursPerDay(int workHoursPerDay) {
this.workHoursPerDay = workHoursPerDay;
}
public int moneyPerHour() {
return weekSalary / (5 * workHoursPerDay);
}
}
public class Program {
public static void main(String[] args) {
ArrayList<Student> student = new ArrayList<>();
ArrayList<Worker> worker = new ArrayList<>();
}
}
Sure, just add the students:
ArrayList<Student> students = new ArrayList<>(); // note: students
students.add(new Student("Jens", "Nenov", "A+"));
You can do almost exactly the same thing for the workers. If you want to use a loop, do the following:
for (int i=0; i<50; i++) {
students.add(new Student("Jens"+i, "Nenov", "A+"));
}
This will create a list of new students with different numbers after their names. If you want different data, though, that data needs to come from somewhere. For example, you might get the data from user input:
Scanner input = new Scanner(System.in);
for ...
System.out.println("Enter a first name:");
String firstname = input.nextLine();
...
students.add(new Student(firstname, lastname, grade));

Java: Storing an Array into an Array?

Is it possible to store three string values added into an array (studentName), and store that into a different array so it can be found later?
Basically my main goal is to store a name, user id, and a balance (fullName, idName, 300).
And add that into a "super(?)" array so when people type down, it finds the fullName and pulls the information from there.
You can create a class
public class Student {
private String name;
private String id;
private int balance;
}
and then you can create a list of these objects:
List<Student> list = new ArrayList<Student>();
Map<String, String> map = new HashMap<String, String>();
then:
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
and then:
map.put("name", "Thomas");
map.put("id", "Thomas id");
map.put("balance", ""300);
listOfMaps.add(map);
Anyhow, be careful. You will have to keep numbers (f.e. balance) as a String and after you will need to map it.
Well, I believe you are talking about something like Jagged Array which is available in C# but for java, we can do it in some other ways... like creating a class and manipulating it as Generic List implementation...
public class Student {
private String name;
private int id;
private int balanace;
public Student(){}
public Student(String name, int id, int balance){
this.name = name;
this.id = id;
this.balanace = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBalanace() {
return balanace;
}
public void setBalanace(int balanace) {
this.balanace = balanace;
}
}
In some other class where you would want to manipulate
public class ManipulateData {
public static void main(String[] args){
Student student1 = new Student("James", 1, 500);
List<Student> list = new ArrayList<Student>();
list.add(student1);
for(Student s: list){
System.out.println("Name : " + s.getName());
System.out.println("ID : " + s.getId());
System.out.println("Balance : " + s.getBalanace());
}
}
}

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