Dynamically fill in an ArrayList with objects - java

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

Related

Cant change method's variables in Java objects

I have a problem with changing variable value in contact object. I'm trying to make a contact list but I can't change value of variables trought methods. I have editContact method which calls changeName method, both methods are passed ArrayList object trought reference so it shouldn't have problems with changing values trought ArrayList in main method, but problem is when I want to change object's name it won't change it. Is there something I'm missing here?
package telefonski_imenik;
public class Contact {
protected String name;
protected String lastname;
protected String number;
public Contact(String name, String lastname, String number) {
setName(name);
setLastName(lastname);
setNumber(number);
}
public void setName(String name) {
this.name = name;
}
public void setLastName(String lastname) {
this.lastname = lastname;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getLastName() {
return this.lastname;
}
public String getNumber() {
return this.number;
}
}
package telefonski_imenik;
import java.util.ArrayList;
import java.util.Scanner;
public class TelefonskiImenik {
public static void createContact(String ime, String prezime, String broj, ArrayList<Contact>
ContactList) {
Contact noviKontakt = new Contact(ime, prezime, broj);
ContactList.add(noviKontakt);
}
public static void editContact(ArrayList<Contact> ContactList) {
System.out.println("Unesite nove podatke");
changeName(ContactList);
}
public static void changeName(ArrayList<Contact> ContactList) {
Scanner novinput = new Scanner(System.in);
System.out.println("Unesite staro ime");
String oldName = novinput.nextLine();
System.out.println("Unesite novo ime");
String newName = novinput.nextLine();
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
novinput.close();
}
public static void main(String[] args) {
ArrayList<Contact> ContactList = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Unesite podatke");
String name = input.nextLine();
String lastname = input.nextLine();
String number= input.nextLine();
createContact(name, lastname, number, ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
editContact(ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
input.close();
}
}
You forgot to get the name of the object in your loop:
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
ContactList.get(i).getName().equals(oldName)

3 separate ArrayList

ACME wants to layoff some employees. Using three ArrayLists, form three lists of employees. The first list will contain all the programmers, the second all the non-programming people making over one hundred thousand dollars, and the last all other people. Using separate loops print out the contents of each ArrayList. (The following are what I did, but not work... looking for help)
import java.util*;
class Employee
{
private String name;
private String address;
private String position;
private double salary;
private String getName()
{return name;}
public String getAddress()
{return address;}
public double getPosition()
{return position;}
public double getSalary()
{return salary;}
public void setName(String aName)
{name=aName;}
public void setAddress(String aAddress)
{address=aAddress;}
public void set(double aPosition)
{postion=aPosition;}
public void setSalary(double aSalary)
{salary=aSalary;}
public employee(String aName, String aAddress, double aPosition; double aSalary)
{
name=aName;
address=aAddress;
position=aPosition;
Salary=aSalary; }
public String toString()
{return name+address+position+salary;}
}
class employee
{public static void main(String[] args)
{Scanner in = new Scanner(System.in);
Employee[] Newemp=new Car[500];
for(int i=0, i<Newemp.length;i++)
{System.out.print(“Enter the name”);
String name=in.nextLine();
System.out.print(“Enter the address”);
String address=in.nextLine();
System.out.print(“Enter the position”);
double position=in.nextDouble();
System.out.print(“Enter the salary”);
double salary=in.nextInt() ;
in.nextLine();
Newemp[i]=new Employee(name, address, position, salary);
}
ArrayList<Employee>programmers=new ArrayList<Employee>();
ArrayList<Employee>nonprogrammers=new ArrayList<Employee>();
ArrayList<Employee>others=new ArrayList<Employee>();
for(int i=0; i<Newemp.salary; i++)
{if(Newemp[i]. getposition().equals(“programmer”))
programmers.add(Newemp[i]);
else if(Employee[i].getsalary()>100000
nonprogrammers.add(Newemp[i]);
else
others.add(Newemp[i]);
}
for(int i=0; i<programmer.();i++)
{
Employee<=programmer.get(i);
System.out.println(i);
}}}
i think this will help
for (int i = 0; i < Newemp.length; i++) {
if (Newemp[i].getPosition().equals("programmer")){
programmers.add(Newemp[i]);
System.out.println("programmers"+programmers);
}
else if (Newemp[i].getSalary()> 100000)
{
nonprogrammers.add(Newemp[i]);
System.out.println("salary 100000 thousand"+nonprogrammers);
} else{
others.add(Newemp[i]);
System.out.println("others"+others);
}
}
for (int i = 0; i < programmers.size(); i++) {
EmployeeData aa= programmers.get(i);
System.out.println("All aaray"+aa);
}
in your main()
for(int i=0; i < Newemp.salary; i++)
...
else if(Employee[i].getsalary()>100000
should be:
for(int i=0; Newemp[i] != null; i++)
...
else if([i].getsalary()>100000)
I hope you understand the concept of object, the methods & variables available with the array can not be mixed with others and vice-versa. length is a variable inside the array object which returns you the size. I would suggest instead of declaring a huge array and then iterating through it. Directly add your objects into an ArrayList as given below. I hope it helps.
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
private String name;
private String address;
private String position;
private double salary;`
public Employee(String aName, String aAddress, String aPosition,
double aSalary) {
name = aName;
address = aAddress;
position = aPosition;
salary = aSalary;
}
private String getName() {
return name;
}
public String getAddress() {
return address;
}
public String getPosition() {
return position;
}
public double getSalary() {
return salary;
}
public void setName(String aName) {
name = aName;
}
public void setAddress(String aAddress) {
address = aAddress;
}
public void set(String aPosition) {
position = aPosition;
}
public void setSalary(double aSalary) {
salary = aSalary;
}
public String toString() {
return name + address + position + salary;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int maxSize = 500;
ArrayList<Employee> programmers = new ArrayList<Employee>();
ArrayList<Employee> nonprogrammers = new ArrayList<Employee>();
ArrayList<Employee> others = new ArrayList<Employee>();
for (int i = 0; i < maxSize; i++) {
System.out.println("Enter the name");
String name = in.nextLine();
System.out.print("Enter the address");
String address = in.nextLine();
System.out.print("Enter the position");
String position = in.nextLine();
System.out.print("Enter the salary");
double salary = in.nextInt();
in.nextLine();
Employee newEmployee = new Employee(name, address, position, salary);
if (position.equals("programmer"))
programmers.add(newEmployee);
else if (salary > 100000)
nonprogrammers.add(newEmployee);
else
others.add(newEmployee);
}
}
}

Java - Adding 2 objects in an ArrayList

I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()

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

Where should i declare the field in this code in order for it to compile?

This is not supposed to be a client class. I'm just making a class for others to use. I'm using this for a Highschool. For example i have classes for the address, teacher, students, principal, roomnumber, etc..But its not compiling for some odd reason. I believe its because I'm not declaring a field but not sure.
import java.io.*;
public class HighSchool {
// Constructors
public HighSchool() { }
public HighSchool(String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects ) {
this.title = title;
this.teacher = teacher;
this.roomNumber = roomNumber;
this.period = period;
this.String[] students = students;
this.String address =a ddress;
this.String subjects = subjects;
}
public class Classcourse (String title, String teacher, int roomNumber, String period, String[] students, String address, String subjects
private String period;) {
public String gettitle() {
return title;
}
public void settitle(String title) {
this.title = title;
}
public String getteacher() {
return teacher;
}
public void setteacher(String teacher) {
this.teacher = teacher;
}
public int getroomNumber() {
return roomNumber;
}
public void setroomNumber (int roomNumber) {
this.roomNumber = roomNumber;
}
public String getperiod() {
return getperiod();
}
public void setperiod (String period) {
this.period = period;
}
public String[] getstudents () {
return students[];
}
public void setstudents[] (String[] students
private String address;) {
this.students = students;
}
public String getaddress() {
return address;
}
public void setaddress (String address) {
this.address = address;
}
public String getsubjects() {
return subjects;
}
public void setsubjects (String subjects) {
this.subjects = subjects;
}
}
// modifier method
public void addstudents(String students) {
String[] newstudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
newstudents[i] = students[i];
}
newstudents[students.length] = student;
students = newstudents;
}
public boolean isInClass(String students) {
for (int i = 0; i < students.length; i++) {
if (students[i].equals(students)) {
return true;
}
}
return false;
}
// static creator method
public static HighSchool readFromInput() throws IOException {
BufferedReader kb = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a HighSchool title: ");
HighSchool newHighSchool = new HighSchool(kb.readLine());
String students = null;
do {
System.out.print("Enter a student, or press Enter to finish: ");
students = kb.readLine();
if (students != null){
newHighSchool.addstudents(students);
}
} while (students != null);
return newHighSchool;
}
// Variables (Fields)
private String title;
private String[] students;
}
In addition, you wrote something that doesn't make sense from the point of view of Java Compiler:
private String period;) {
- probably remove ")".
The second thing:
Take a look on the declaration of class Classcourse.
It rather sounds wrong, although it can be an issue of this site's editor or something...
An "overall" hint - java has a very "intelligent" compiler in the most of the cases it can say what's wrong exactly with your code, so, assuming you're a newbie in Java, try to understand what compiler says to you.
Good luck!
Some things I noticed about the code:
public String getperiod() {
return getperiod();
}
This code will cause a endless loop when you call this function.
private String address;) {
this.students = students;
}
The compiler will give an error about the ";)". Change it to "()" to fix this.
Furthermore, you should really tell us more about the errors it's giving you. We can't help you if you don't give us the compiler errors.

Categories

Resources