move an object from one array list to another - java

I have a class that has private variables such as employeeName and employeeNumber and methods to set and get employeeName and employeeNumber. This class is called "EmployeesInformation". In this class I have two constructors. One that gets employee's information such as EmployeesInformation(String name, String phoneNumber){...} and another one that gets the same information but also receives two additional bits of information such as String datefired and String reasonForLeave.
Now in another class called "MenuOptionMethods" I have the addEmployee method and fireEmployee method and another method to show employees information.
I created two arrayList in this class called employee and formerEmployee.
Whenever the user adds an employee I put that employee object in the arrayList called employee. When the user fires or removes an employee I want to take all of that employee's information, remove it from arrayList employee and add it to arrayList formerEmployee. That is where I'm having problems. Can someone take a look at my code and tell me what's wrong with it?
public class menuOptionMethods {
Scanner sc = new Scanner(System.in);
private ArrayList<EmployeesInformation> employee;
private ArrayList<EmployeesInformation> formerEmployee;
public menuOptionMethods() {
employee = new ArrayList<EmployeesInformation>();
formerEmployee = new ArrayList<EmployeesInformation>();
}
public void addEmployee(String eName) {
String n = eName;
System.out.println(" Enter date hired: ");
String h = sc.next();
System.out.println(" Enter employee's duty: ");
String d = sc.next();
System.out.println(" Enter employee's phone number: ");
String pN = sc.next();
System.out.println(" Enter employee's pay per hour: ");
double pPH = sc.nextInt();
System.out
.println(" Enter any additional information about employee: ");
String l = sc.next();
EmployeesInformation e = new EmployeesInformation(n, h, d, l, pN, pPH);
employee.add(e);
}
public void fireEmployee(String eName) {
// System.out.println("Enter employee's name: ");
// String name = eName;
System.out.println("Reason for employee's leave?: ");
String reason = sc.next();
System.out.println("Enter date: ");
String dF = sc.next();
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
n = eName;
h = employee.get(i).getDateHired();
d = employee.get(i).getEmployeDuty();
pH = employee.get(i).getPhoneNumber();
pPH = employee.get(i).getEmployePay();
l = employee.get(i).getAdditionalInformation();
employee.remove(i);
}
}
EmployeesInformation fE = new EmployeesInformation(n,h,d,l,pH,pPH,reason,dF); // ERROR HAPPENS HERE
}
}

You can't remove element from list while iterating it with for loop (it will throw ConcurrentModificationException. To do that, you need to use iterator and call remove() method, e.g.:
for(Iterator<Employee> iterator = employees.iterator() ; iterator.hasNext();){
Employee current = iterator.next();
if(current.getName().equals(name)){
iterator.remove();
//Add into former employees' list
break;
}
}
This will remove from existing list.

In your for loop, you don't want to do any removing because the size of the arraylist will change, and that just creates whack that is throwing you off. Assuming every employee has a unique name, you could do something like this (note I simplified making all those new variable by just transferring that employee object from one arraylist to the other):
int index;
for(int i=0; i<employee.size(); i++){
if(employee.get(i).getEmployeName().contains(eName)){
formerEmployee.add(employee[i]); //date fired and reason fired can be added later
index = i;
break;
}
}
employee.remove(i);
}

Related

User input to update variables when multiple objects involved

I'm currently learning java and starting on methods, classes and objects. I'm attempting to code a simple program to have set values for 2 separate employee's at a company that would then allow for user input to alter certain variables of a specific object. The variables needing to be updated via user input will be the MonthlySalary and FirstName of the object employee2. I'm not really sure how to structure the user input part and I'm at a loss trying to find a solution.
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String[] args ){
Scanner input = new Scanner(System.in);
// Create 2 Employee objects
Employee employee1 = new Employee( "Jane", "Doe", 5000 );
Employee employee2 = new Employee( "John", "Bloggs", 4500 );
// Do other steps (not requiring input)
// Ask for user input of Employee 2's new first name
System.out.println( "Please enter new first name for Employee 2: \n");
String input = employee2.newFirstName();
// repeat above to set Employee 2's new salary then display new information
}
}
With the Class file Employee.java
public class Employee
{
private String firstName; // Employee's First Name
private String lastName; // Employee's Last Name
private double monthlySalary; // Employee's Monthly Salary
// Employee constructor
public Employee( String initFirstName, String initLastName, double initMonthlySalary )
{
firstName = initFirstName;
lastName = initLastName;
if (initMonthlySalary > 0)
monthlySalary = initMonthlySalary;
else
monthlySalary = 0;
}
public Employee( )
{
firstName = "";
lastName = "";
monthlySalary = 0;
}
// Method to assign the employee's First Name
public void setFirstName( String newFirstName )
{
firstName = newFirstName;
}
// Method to assign the employee's Monthly Salary
public void setMonthlySalary( double newMonthlySalary )
{
if (newMonthlySalary > 0) monthlySalary = newMonthlySalary;
}
// Other required methods
}
You are struggling to take input from the console.
System.out.println("Please enter new first name for Employee 2: ");
String firstName = input.next();
employee2.setFirstName(firstName);
System.out.println("Please enter new Salary for Employee 2: ");
double salary = input.nextDouble();
employee2.setMonthlySalary(salary);
This will work for you. And please go through the basic syntaxes first. Because otherwise you are wasting your own time banging your head for this kind of syntactical doubts.

Looping new objects in Java and passing values from getMethods?

I want to know how I can loop a new object within the same class, so that I can repeat the code to have several different objects with different details entered via the Scanner class.
It will probably make sense if I show what I am trying to do:
public class Students
{
private String studFirstName; // Student's first name
private String studSurname; // Student's surname
private String courseName; // Course name
public Students(String sFirstName, String sSurname, String cName)
{
studFirstName = sFirstName;
studSurname = sSurname;
courseName = cName;
}
public String getStudFirstName() // Getter for student's first name
{
System.out.println("Enter in student's first name: "); // Prompts end user for input
Scanner In = new Scanner(System.in); // Creating a new object
studFirstName = In.next(); // Accepts a one word input only
return studFirstName;
}
public String setStudFirstName(String sFirstName) // Setter for student's first name
{
return studFirstName;
}
public static void main (String [] args)
{
Students first[] = new Students[5];
for(Students a : first)
{
}
Students first[] = new Students("", "", "");
String studFirstName = first.getStudFirstName();
}
}
You need a regular for loop in order to assign values within the array.
int numStudents = 5;
Student students[] = new Student[numStudents]; // creates an array of 5 nulls
Scanner scan = new Scanner(System.in);
for(int i = 0; i < numStudents; i++) {
System.out.println("Enter your first name: "); // Prompt
String fname = scan.nextLine(); // Read
Student s = new Student(fname); // Assign
first[i] = s; // Store
}
You really don't need the get methods since you have access to set the values in the constuctor.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Student[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(studFirstName);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());
}
}
First, you should take a look at encapsulation. A getter is not meant to take user input. Getter should return the value of a private field. Setters should set the value of a private field.
// This is a field
private String myField;
// This will return the current value for the field 'myField'
public String getMyField() {
return this.myField;
}
// This will asign a new value to the field 'myField'
public void setMyField(String myField) {
this.myField = myField;
}
Answer
You will need a regular for loop to create as many students a you want. I renamed your class 'Students' to Student to fit javas naming conventions.
int numberOfStudents = 3;
// create an array that can hold up to 3 students
Student[] students = new Stundent[numberOfStudents];
// create the Scanner to read from console.
Scanner scanner = new Scanner(System.in);
// create the 3 students and store them in the array
for(int i = 0; i < numberOfStudents; i++) {
System.out.println("Enter name: ");
// read the next line from the console
String name = scanner.nextLine();
// ...
// if you have anything you need to create the student object (e.g. name, and so on).
Student s = new Student(name, .....);
students[i] = s; // store the student object in the array.
}
// you should evt. close the scanner
// scanner.close();
// you can now do anything with your 3 stored students.
System.out.println("The Students first name is: " + students[0].getStudFirstName());

Assigning and returning objects in java

I am trying to assign the current array element in the temp array with the Student object returned after calling the getStudent method.... I called the getStudent method (Step 2) and have temp[i] = to assign the current element in the temp array but cannot figure out what it should = to pair it up with the Student object returned. When using getStudent() and running the program, the output is enter the number of students, the user enters the number, and that is all that happens, it does not ask for the user to enter the name and etc, I'm not sure if step 2 is the problem or if there is another issue entirely.
import java.util.Scanner;
public class Students
{
private static Scanner input = new Scanner(System.in);
public static void main(String[] args)
{
Student[] students;
students = getStudents();
printStudents(students);
}
private static Student[] getStudents()
{
Student[] temp;
int how_many;
System.out.print("How many students? ");
how_many = input.nextInt();
purgeInputBuffer();
temp = new Student[input.nextInt()]; // Step 1 ???
for (int i = 0; i < temp.length; i++)
{
getStudent(); // Step 2
temp[i] = ; // <----------
}
return temp; // Step 3
}
private static Student getStudent()
{
String name,
address,
major;
double gpa;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.print("Enter address: ");
address = input.nextLine();
System.out.print("Enter major: ");
major = input.nextLine();
System.out.print("Enter GPA: ");
gpa = input.nextDouble();
purgeInputBuffer();
return new Student (name, address, major, gpa); // Step 4
}
private static void printStudents(Student[] s)
{
System.out.println();
for (int i = 0; i < s.length; i++) // Step 5
{
System.out.println(getStudent()); // Step 6
}
}
private static void purgeInputBuffer()
{
// ----------------------------------------------------
// Purge input buffer by reading and ignoring remaining
// characters in input buffer including the newline
// ----------------------------------------------------
input.nextLine();
}
}
So first problem is first on the line:
temp = new Student[input.nextInt()];
in that line you have already asked the user to enter how many Students and store it in how_many. So i'm assuming you want to instead do:
temp = new Student[how_many];
Also what i said in my comment:
But please do also look at your private static void printStudents(Student[] s) method and acutally on the line //step 6 i don't believe that is how you want to be doing that. Instead you want System.out.println(s[i]); not System.out.println(getStudent()); For my code substitution to work though you will need to Override the toString method so it can actually display the information

Java : How to create an array from object then store String and double in that array

I want to create an array from object then store in that array with 2 different type of date
i'm still learning java and this is kinda my task and i searched many times and have find nothing so please i need your help :D
the base class :
package com.matcho.task;
public class Subject {
String name;
Double grade;
public Subject(String myname, double myGrade) {
name = myname;
grade = myGrade;
}
public void printermethod() {
System.out.println("Your Subject is " + name + " and ur grade is "
+ grade);
}
}
and this is the main class :
package com.matcho.task;
import java.util.Scanner;
public class subjectUseing {
public static void main(String[] args) {
String studentName = "";
double studentGrade = 0;
Subject object1 = new Subject(studentName, studentGrade);
Scanner input = new Scanner(System.in);
System.out.print("Please, Enter the Size of the Array : ");
int arraySize = input.nextInt();
Subject[] gradeArray = new Subject[arraySize];
for (int i = 0; i < gradeArray.length; i += 2) {
if ((i + 1) % 2 == 0) {
System.out.println("Please, Enter Subject Number Grade");
studentGrade = input.nextDouble();
studentGrade = object1.grade;
gradeArray[i] = object1.grade;
//Error said (cannot convert from Double to Subject)
//object1.grade = (Double)gradeArray[i];
//gradeArray[i] = object1.grade;
continue;
} else {
System.out.println("Please, Enter Subject Number Name");
studentName = input.next();
studentName = object1.name;
//Error said (cannot convert from String to Subject)
gradeArray[i] = new Subject(object1.name, object1.grade);
// gradeArray[i] = object1.name;
// gradeArray[i] = new String(object1.name); // Failed T_T
}
}// For End
for (int i = 0; i < gradeArray.length; i += 2) {
System.out.println("Your Grade in each Subject is : "
+ gradeArray[i] + " " + gradeArray[i + 1]);
}// For End
}
}
i tried many ways and search many times but found nothing so please i need help because this error
[cannot convert from Double to Subject] blow up my mind :D
You basically need to simplify your loop: on each iteration of the loop, ask for both the subject name and the grade, then create one object to store them both:
for (int i = 0; i < gradeArray.length; i++) {
System.out.println("Please enter the subject name");
String name = input.next();
System.out.println("Please enter the subject grade");
double grade = input.nextDouble();
gradeArray[i] = new Subject(name, grade);
}
Note the declaration of the variables inside the loop - you don't need them outside the loop, so don't declare them there.
Then for display, you'd just use:
for (Subject grade : gradeArray) {
System.out.println(grade);
}
Again, there's no need to skip every other item in the array - each element in the array is a reference to a Subject object, which contains both a name and a grade.
(Or add getName and getGrade methods to Subject so that you can customize the output.)
Note that you may find Scanner a bit of a pain to work with - nextDouble() won't consume a line break, for example, which may mean you get an empty string when reading the next name. You might want to consider just reading a line at a time and using Double.parseDouble to parse a string. (Or use NumberFormat.)
By Definition
An array is a container object that holds a fixed number of values of a single type
You can not create an array then fill it with values of other types.
In your code you've created an array of Subject then all it's elements should be of type Subject , The members of Subject class doesn't matter at this point the array should handle Elements of type Subject.
In your logic "Business requirements " you're asked to create an array which holds the values of Student subject plus their Grades , then you say OK Easy task and you create the array and then you try to store grades and names of an object of Subject Class in the array Saying that
" Object is a reference type , and so as it's members " but NO!! it's not;
Your array should contains only Subject Elements
Take a look in the correct solution:
Scanner in = new Scanner(System.in);
System.out.println("Enter array size");
int size = in.nextInt();
Subject[] subjects = new Subject[size];
String name;
Double grade;
Subject object;
for(int i =0; i<size; i++)
{
System.out.println("Enter Subject name: ");
name=in.next();
System.out.println("Enter Subject Grade: ");
grade = in.nextDouble();
object = new Subject(name,grade);
subjects[i] = object;
}
for(int i=0; i<size; i++)
System.out.println("Subject name is "+subjects[i].name + " Grade is "+subjects[i].grade);
}
You created an array of Subject objects, but you are storing Double.
studentGrade = object1.grade;
gradeArray[i] = object1.grade;
You should store it like:
object1.grade = studentGrade;
gradeArray[i].grade = object1.grade;
But as already mentioned, you don't need so many local variables. You could dou it lik:
gradeArray[i].grade = input.nextDouble();

Reading user input into array

I need to store user input in an array, but I am having trouble accomplishing this. Can anyone offer some advice?
import java.util.Scanner;
public class EmployeeManagement {
Scanner s = new Scanner(System.in);
Employee e = new Employee();
Employee[] arrayOfEmp = new Employee[2]; //Fields
public static int index;
public void addRecord(Employee userE, int index){ //Add method
while(index<arrayOfEmp.length){
System.out.println("Please enter Employee Id : ");
e.setEmployeeId(s.next());
System.out.println("Please enter Employee Name : ");
e.setName(s.next());
this.arrayOfEmp[index]=userE;
index++;
}
That should be because you don't append the right value in your array. You append "userE" which is a parameter, but you set values inside "e", which is another Employee instance.
Scanner s = new Scanner(System.in);
Employee[] arrayOfEmp = new Employee[2]; //Fields
public int index;
public int addRecord(int index){ //Add method
while(index<arrayOfEmp.length){
Employee e = new Employee();
System.out.println("Please enter Employee Id : ");
e.setEmployeeId(Integer.parseInt(s.nextLine()));
System.out.println("Please enter Employee Name : ");
e.setName(s.nextLine());
this.arrayOfEmp[index++]=e;
return index;
}
to invoke it please use
index = addRecord(index);
then your variable index will be updated by local index var in method.
s.next() changed to nextLine()
Since, names for example [SUBASH PRAKASH] can be with spaces you have to use nextLine().
For any other integers use nextInt()
And u should be calling using this as reference : Employee e = new Employee();

Categories