How to print a certain part of an Array? - java

i'm in need of assistance with a small error in my code. I have a program that has 4 String Arrays that i have to combine and print in separate places using constructors. I need to write a method: Employee[] searchWithId(Employee[] list, String search) which searches for a string in the array and returns the matched string along with the other corresponding information.
For example:
searchWithId(list, "P102432"); // search the list for the given id
Output:
Searching for the id number:P102432 ...
Found the record for the id number:P102432
first name:Amber Last Name:Nogofski
Id number:P102432
Employee number:No employee number has been assigned yet!
Heres my code so far:
Employee Class:
public static class Employee {
private String firstName;
private String lastName;
private String idNumber;
private String employeeNumber;
private int employeeCount;
/**
* Constructor
*
* #param firstName first name
* #param lastName last name
* #param idNumber id number
*/
public Employee(String firstName, String lastName, String idNumber) {
this.firstName = firstName;
this.lastName = lastName;
this.idNumber = idNumber;
employeeCount = 0;
}
/**
* Accessors here
*/
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getIdNumber() {
return idNumber;
}
public String getEmployeeNumber() {
return employeeNumber;
}
// mutators here
/**
* #param firstName first name
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* #param lastName last name
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* #param idNumber id number
*/
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
/**
* #param employeeNumber employee number
*/
public void setEmployeeNumber(String employeeNumber) {
this.employeeNumber = "";
}
#Override
public String toString() {
String result = "First name: " + getFirstName() + "\nLast name: " + getLastName()
+ "\nId number: " + getIdNumber() + "\nEmployee number: ";
if (getEmployeeNumber() == null) {
return result + "No employee number has been assigned yet!\n";
}
return result + getEmployeeNumber() + "\n";
}
}
My main and other methods:
public static void main(String[] args) {
String[] firstNames = {"Fred", "John", "Amir", "James", "Bob", "Jay", "Amber"};
String[] lastNames = {"Bond", "Kates", "Memar", "White", "Marley", "Brown", "Nogofski"};
String[] idNumbers = {"R111111", "A222222", "AB11111", "KR22121", "V311133", "L242434", "P102432"};
String[] employeeNum = {"1111", "2222", "3333", "4444", "5555", "6666", "7777"};
Employee[] list = new Employee[firstNames.length];
list = listOfEmployees(firstNames, lastNames, idNumbers); // create the list of employees in one array
System.out.println("List of employees before sorting...\n");
printEmployeeList(list); //print the list of employees
System.out.println(); // new line
searchWithId(list, "P102432"); // search the list for the given id
searchWithLastName(list, "Bond"); // search the list for the given last name
System.out.println(); // new line
searchWithId(list, "P1024444"); // search the list for the given id
searchWithLastName(list, "BoNd"); // search the list for the given last name
System.out.println();// new line
sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
list = assignEmployeeNum(list, employeeNum); // assign the employee number to the employees
System.out.println("+++After adding the employee number to the list+++");// new line
printEmployeeList(list); // print the list again with the employee number
searchWithEmployeeNum(list, "5555"); // search the list for the given employee number
sortWithFirstName(list); // sort the employee list and then call appropriate method to print it.
}
public static Employee[] listOfEmployees(String[] firstName, String[] lastName, String[] idNumber) {
Employee[] list = new Employee[firstName.length];
for (int i = 0; i < list.length; i++) {
list[i] = new Employee(firstName[i], lastName[i], idNumber[i]);
}
return list;
}
public static void printEmployeeList(Employee[] list) {
Arrays.stream(list).forEach(System.out::println);
}
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
for (int i = 0; i < list.length; i++) {
if (list[i].getIdNumber().equals(search)) {
System.out.println("Found id number: " + search);
//Arrays.toString(list); <- my try
}
}
return list;
}

You can do it as follows:
import java.util.Arrays;
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee[] filteredEmployees = new Employee[list.length];
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getIdNumber().equalsIgnoreCase(search)) {
filteredEmployees[index++] = list[i];
}
}
// It'll remove the null values:
return Arrays.copyOfRange(filteredEmployees, 0, index);
}
Java 8 Version:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
return Arrays.asList(list)
.stream()
.filter(e -> e.idNumber.equalsIgnoreCase(search))
.collect(Collectors.toList())
.toArray(new Employee[list.length]);
}

change your searchWithId method to mine:
first way is using ArrayList of Employees
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
ArrayList<Employee> search_result = new ArrayList<>();
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
search_result.add(employee);
}
}
return search_result.toArray(new Employee[search_result.size()]);
}
or you can use array of employee to do this
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee search_result[] = new Employee[list.length];
int index = 0;
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
search_result[index] = employee;
index++;
}
}
return Arrays.copyOfRange(search_result, 0, index);
}
even you can use
public static Employee[] searchWithId(Employee[] list, String search) {
System.out.println("Searching for the id number: " + search);
Employee first_search_result[] = new Employee[list.length];
int index = 0;
for (Employee employee : list) {
if (employee.getIdNumber().equals(search)) {
first_search_result[index] = employee;
index++;
}
}
Employee final_search_result[] = new Employee[index];
for (int i=0; i<first_search_result.length;i++) {
if (first_search_result[i].getIdNumber().equals(search)) {
final_search_result[i] = first_search_result[i];
}
}
return final_search_result;
}
and return final_search_result, to avoid using Arrays.copyOfRange
the above method in any way will return list of all employees with search id

Related

Java Arrays and Referencing

As part of the curriculum at my school, we are working on some CodeHS Java.
There is one problem that I'm stuck on:
Taking our Student and Classroom example from earlier, you should fill in the method getMostImprovedStudent, as well as the method getExamRange. The most improved student is the one with the largest exam score range.
To compute the exam score range, you must subtract the minimum exam score from the maximum exam score.
For example, if the exam scores were 90, 75, and 84, the range would be 90 - 75 = 15.
This is the Student class which I added my method getExamRange().
import java.util.*;
public class Student
{
private static final int NUM_EXAMS = 4;
private String firstName;
private String lastName;
private int gradeLevel;
private double gpa;
private int[] exams;
private int numExamsTaken;
public static int[] examRange = new int[Classroom.numStudentsAdded];
private int i = 0;
/**
* This is a constructor. A constructor is a method
* that creates an object -- it creates an instance
* of the class. What that means is it takes the input
* parameters and sets the instance variables (or fields)
* to the proper values.
*
* Check out StudentTester.java for an example of how to use
* this constructor.
*/
public Student(String fName, String lName, int grade)
{
firstName = fName;
lastName = lName;
gradeLevel = grade;
exams = new int[NUM_EXAMS];
numExamsTaken = 0;
}
public int getExamRange()
{
Arrays.sort(exams);
examRange[i] = exams[exams.length-1] - exams[0];
i++;
return exams[exams.length-1] - exams[0];
}
public String getName()
{
return firstName + " " + lastName;
}
public void addExamScore(int score)
{
exams[numExamsTaken] = score;
numExamsTaken++;
}
// This is a setter method to set the GPA for the Student.
public void setGPA(double theGPA)
{
gpa = theGPA;
}
/**
* This is a toString for the Student class. It returns a String
* representation of the object, which includes the fields
* in that object.
*/
public String toString()
{
return firstName + " " + lastName + " is in grade: " + gradeLevel;
}
}
And this is the Classroom class in which I added the method getMostImprovedStudent().
import java.util.*;
public class Classroom
{
Student[] students;
static int numStudentsAdded;
public Classroom(int numStudents)
{
students = new Student[numStudents];
numStudentsAdded = 0;
}
public Student getMostImprovedStudent()
{
Arrays.sort(Student.examRange);
//return Student.examRange[0];
}
public void addStudent(Student s)
{
students[numStudentsAdded] = s;
numStudentsAdded++;
}
public void printStudents()
{
for(int i = 0; i < numStudentsAdded; i++)
{
System.out.println(students[i]);
}
}
}
I can get the exam Range by sorting the exams array then subtracting the smallest from the biggest, but once I do this, how do I find the student with the biggest exam range, and return it?
The way you would do this is looping through students, and have a variable to hold the biggest difference in score, and the most improved student:
public Student getMostImprovedStudent()
{
Student mostImproved = students[0];
int biggest = student[i].getExamRange();
for(int i = 1; i < students.length; i++) {
if(students[i].getExamRange() > biggest) {
mostImproved = students[i];
biggest = students[i].getExamRange();
}
}
return mostImproved;
}
However Java 8+ we can do:
public Student getMostImprovedStudent()
{
return Arrays.stream(students)
.max(Comparator.comparing(Student::getExamRange))
.get();
}
Which is assuming that students is not empty
As I explained in the comment above you can do it this way:
public Student getMostImprovedStudent() {
Student maxRangeStudent = null;
int maxRange = 0;
for (Student student: students) {
int curExamRange = student.getExamRange();
if (curExamRange > maxRange){
maxRangeStudent = student;
maxRange = curExamRange;
}
}
return maxRangeStudent;
}

ArrayList not returning expected data

I don't know what I'm doing and would appreciate any help.
I'm reading a text file with the following code:
7
10 416-555-6667 Burgess Smith 15
15 905-777-8888 Thomas Patel 10
20 905-111-2222 Morris J. Stevenson 5
25 416-222-3333 Spencer Larson 30
30 416-333-4444 Adams Doe 18
35 905-122-5454 Price Hanks 15
40 905-343-5151 Clement L. Webster 8
private static void fileReader() throws FileNotFoundException
{
int eId = 0;
String nme = "";
String phne = "";
int yrs = 0;
String line ="";
Employee emp = new Employee(eId, nme, phne, yrs);
File inputfile = new File("Emp.txt");
Scanner in = new Scanner(inputfile);
n = in.nextInt() - 1;
in.nextLine();
in.useDelimiter("");
for (int i=0;i<=n;i++)
{
int l = 0;
int m = 0;
int n = 0;
line = in.nextLine();
while (Character.isDigit(line.charAt(l)))
{
l++;
}
m = l + 1;
while (!Character.isLetter(line.charAt(m)) && !Character.isWhitespace(line.charAt(m)))
{
m++;
}
n = m + 1;
while (!Character.isDigit(line.charAt(n)))
{
n++;
}
eId = Integer.parseInt(line.substring(0, l));
emp.setEmpId(eId);
phne = line.substring(l + 1, m - 1);
emp.setTelephone(phne);
nme = line.substring(m + 1, n - 1);
emp.setName(nme);
yrs = Integer.parseInt(line.substring(n));
emp.setYears(yrs);
empArr.add(i, emp);
}
in.close();
}
class for set and get methods:
public class Employee
{
private int empId;
private String telephone;
private String name;
private int yearsOfWork;
public Employee(int id, String name, String telephone, int yearsOfWork)
{
empId = id;
this.telephone = telephone;
this.name = name;
this.yearsOfWork = yearsOfWork;
}
public void setEmpId(int id)
{
empId = id;
}
public void setName(String name)
{
this.name = name;
}
public void setTelephone(String telephone)
{
this.telephone = telephone;
}
public void setYears(int years)
{
yearsOfWork = years;
}
public int getEmpId()
{
return empId;
}
public String getName()
{
return name;
}
public String getTelephone()
{
return telephone;
}
public int getYears()
{
return yearsOfWork;
}
public String toString()
{
return "ID:" + empId + ", name: " + name + ", phone: " + telephone + ", years of work: " + yearsOfWork + "\n";
}
}
When I call the get method of my ArrayList outside of its for loop, the text at each index is overwritten by the text at the last index.
I think I'm missing some fundamental concept of constructors and objects here.
Any help is appreciated. Thanks.
Your hunch is correct, you are missing the emp object creation. You have to move the emp object creation into the loop.
Your Employee class and getter/setter methods are correctly written.
Rewrite your fileReader() method similar to given below : -
String line ="";
//Declare an Arraylist for an Employee
List<Employee> employee = new ArrayList<Employee>();
//Read a file
File inputfile = new File("Emp.txt file path");
Scanner in = new Scanner(inputfile);
//Reading a number from a first sentence
int n = Integer.parseInt(in.nextLine());
for (int i=0;i<n;i++) {
// Reading each sentence
line = in.nextLine();
//Parse an Emp id
int eId = Integer.parseInt(line.substring(0, 2));
//Parse a phone number
String phone = line.substring(3, 14);
//Parse a name
String name = line.split("\\d+")[4];
//Parse years
int years = Integer.parseInt(line.split("\\D+")[4]);
//Now create an object by putting all above values in a constructor
Employee emp1 = new Employee(eId, name, phone, years);
//Add that object in an arraylist
employee.add(emp1);
}
//As you have overridden toString method, print an arraylist
System.out.println(emp.toString());
//Closing the scanner
in.close();
}
Hope this helps.

How to assign a number to an object in an array?

package chapter10;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Customer {
private String name;
private String streetAddress;
private String phoneNumber;
private int total;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreetAddress(){
return streetAddress;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getTotal(){
return total;
}
public void setTotal(int total){
this.total = total;
}
public static void assign(){
int a = (int) (Math.random() + 10);
int r = (int) (Math.random() + 10);
int f = (int) (Math.random() + 10);
System.out.println(a + r + f + "x" + "x" + "x");
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
ArrayList <Customer > customerList = new ArrayList <Customer>();
char ans;
do
{
Customer customer = new Customer();
System.out.print("Customer name ");
customer.setName(in.next());
int i = 0;
++i;
System.out.print("Street Address ");
customer.setStreetAddress(in.next());
System.out.print("Phone Number ");
customer.setPhoneNumber(in.next());
customerList.add(customer);
System.out.println("Enter total sales ");
customer.setTotal(in.nextInt());
System.out.println("Would you like to enter in a new customer ( y/n)? ");
String answer = in.next();
ans = answer.charAt(0);
((String) customerList).concat("")
} while(ans == 'y');
for(Customer c: customerList){
System.out.print(c.getName() + "\n" + "Phone number is " +c .getPhoneNumber() +"\n" + "Total sales is "+ c.getTotal() + "\n" + "Address is"+ c.getStreetAddress());
}
for(int i=0; i<customerList.size(); i++){
//System.out.print(customerList.get(i).getName());
}
}
}
I need to assign a number to each value in the arraylist but i am getting an error that says that I have to convert to string (arraylist). How do I add it?
If what I gather from the comments is correct then I believe this is what you want:
Your current assign() is incorrect if you want random values 1-10, it should look like this instead:
public String assign(){
Random rand = new Random();
int a = rand.nextInt(10) + 1;
int r = rand.nextInt(10) + 1;
int f = rand.nextInt(10) + 1;
return a+r+f+"xxx";
}
Customer will look like this:
public class Customer {
private String name;
private String customerNumber;
private String streetAddress;
private String phoneNumber;
private int total;
...
...
...
public String getCustomerNumber() { return this.customerNumber; }
public void setCustomerNumber(String cNumber) { this.customerNumber = cNumber; }
And assigning the numbers should look like this:
for(Customer c : customerList) {
c.setCustomerNumber(assign());
}
Also avoid this line of code, it's a really bad idea:
((String) customerList).concat("")
You should probably rename the customerNumber to customerID.
Hiiii
As i understand you are trying to to add number to each value to arrayList ,And same time you are creating arrayList of customer object, So first understand about arrayList of object,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Customer> al = new ArrayList();
al.add(c1);
al.add(c2);
Here this ArrayList object save only address of customer object so how can you change the address of Customer object ; You can not add number in Customer type ArrayList Object,
There is another way typecast your ArrayList to Object type and then no need to typecast again , you can add any type of object in ArrayList
like this,
Customer c1 = new Customer();
Customer c2 = new Customer();
ArrayList<Object> al = new ArrayList();
al.add(c1);
al.add(c2);
In your code there's the following line:
((String) customerList).concat("")
Trying to cast a List to a String is doomed to failure - I'm not sure why do you think it should work.
If you want a String representation of the list, you should implement a toString() method in class Customer and then you can do something like:
System.out.println(Arrays.toString(customerList.toArray()));
Instead of using ArrayList, you can use Map. In which you can have the number as key and value as Customer.
http://examples.javacodegeeks.com/java-basics/java-map-example/ Contains the example of using Map
Answer in Storing a new object as the value of a hashmap? contains info about how to use Object as value in HashMap

array of string in java

I want to solve this problem without using arraylist.
i want to add the contact to its specific index in the array of strings. And then display all the added contacts in string format seperated by commas.
My code gives the result of only last added contract:
Contact [first=Bob, last=Moore, number=555-9756]
where is the problem in my code?
Is there any idea how to solve???
This class consist of the main method:
This is the main class:
public class ExampleApp {
public static void main(String[] args) {
PhoneBook pb = new PhoneBook("Personal book");
System.out.println( pb.getName() );
pb.add("Alice", "Green", "555-1234");
pb.add("Mary", "Smith", "555-6784");
pb.add("Bob", "Moore", "555-9756");
System.out.println( pb.toString() );// here i want to display all the contracts seperated by commas
System.out.println( pb.first() );// first contract
System.out.println( pb.get(2) );// second contract
String toBeFound = new String("Moore");
System.out.println( pb.find(toBeFound) );// display the found contract
}
}
This is the phonebook class:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
/**
* Create a new phonebook with given name
*/
public PhoneBook(String name) {
this.name = name;
}
/**
* Return the phonebook name
*/
public String getName() {
return name;
}
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
for(int i=0;i<MAX;i++){ // i added for each array index the contracts strings
contracts[i]= c.toString();
}
}
/**
* Return the first contact
*/
public String first() {
return get(1);
}
/**
* Return the i-th contact (supposing that first
* index is 1)
*/
public String get(int i) {
String s =contracts[i].toString();
return s;
}
/**
* Return a string containing the list of textual
* representation of all contacts, separated by ", ".
* List starts with "("and ends with ")"
*/
public String toString() {
String s= " ";
for(int i=1;i<MAX;i++){ // here i tried to display the string looping the array
s=contracts[i].toString();
}
return s;
}
/**
* Return the textual representation of first
* contact containing "needle"
*/
public String find(String needle) {
//TODO: to be implemented
return null;
}
}
This is the contact class :
public class Contact {
public String first;
public String last;
public String number;
public String[] contacts;
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public String getFirst() {
return first;
}
public void setFirst(String first) {
this.first = first;
}
public String getLast() {
return last;
}
public void setLast(String last) {
this.last = last;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
You can use ArrayList for it. It will help you really much and you should make your veriables private.
private String first;
private String last;
private String number;
private ArrayList<String> list = new ArrayList<String>();
for(String pointer : list){
}
or you can make contact saver ArrayList
private ArrayList<Contact> list = new ArrayList<Contact>();
public Contact(String first, String last, String number) {
this.first=first;
this.last = last;
this.number=number;
}
public void add(String first, String last, String number){
c=new Contact(first,last,number);
list.add(c);
}
and you can access all veriables like that list.get(i).first.
You can save your contact class and contracts array in arraylist and it will give you more power to access. If you want to display your ArrayList, which index is not important, you need only ++i for it.
I changed your class look this:
public class PhoneBook {
public static final int MAX = 10;
public String name;
String[] contracts = new String[MAX]; // i created an array of strings
Contact c;
private int count = 0;// saved last index of array
public PhoneBook(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void add(String first, String last, String number) {
c = new Contact(first, last, number);
contracts[count] = c.toString(); // save your String inside of last index++
count++;
}
public String first() {
return get(1);
}
public String get(int i) {
String s = contracts[i].toString();
return s;
}
public String toString() {
for (int i = 0; i < MAX; i++) {
if (contracts[i] != null)
System.out.println(contracts[i].toString());
}
return "";
}
public String find(String needle) {
return null;
}
}
public class Contact {
public String first;
public String last;
public String number;
public Contact(String first, String last, String number) {
this.first = first;
this.last = last;
this.number = number;
}
#Override
public String toString() {
return "Contact [first=" + first + ", last=" + last + ", number="
+ number + "]";
}
}
//Personal book
//Contact [first=Alice, last=Green, number=555-1234]
//Contact[first=Mary, last=Smith, number=555-6784]
//Contact [first=Bob, last=Moore, number=555-9756]
you always delete your last toString method. Your Add method is wrong. You always turn 0 and write again inside of array.
You should keep track of the last contact added to your array :
private int lastIndex = 0; // index of first available index of the array
...
/**
* Insert a new contact at the end
*/
public void add(String first, String last, String number){
c=new Contact(first,last,number);
if (lastIndex < MAX)
contracts[lastIndex++]= c.toString();
}
Some other issues with your code :
/**
* Return the first contact
*/
public String first() {
return get(1); // should be get(0)
}
Calling toString() for contracts[i] is redundant, since it's already a String. Perhaps you meant to store Contact instances instead of Strings in your array? That would make more sense.
Add an extra variable static int Last = 0; To track how many contact you have added and update the add function as .
public void add(String first, String last, String number){
if(Last>=MAX){
System.out.println("Error in adding\n");
}
else{
c=new Contact(first,last,number);
contacts[Last] = c.toString();
Last++;
}
}
Change Tostring() for loop to last. So that you will be printing only added contact .In your case you are printing upto MAX that is wrong when less no of contacts are added.
You have to pass i=0,1,2,...,MAX-1 to get(i) function . Array is Zero(0) based indexed.
So, the problem you are having is that you always retrieve the last contact, regardless of which one you try to get. This is because when you add a new contact, you are actually replacing ALL the contacts, making them all the same. You are getting the correct contact from the phonebook, but they ALL have the same value.
To fix it, do the following:
public class PhoneBook
{
int contactsAdded = 0; // Add an integer to store how many contacts you have added
Contact[] contacts = new Contact[MAX]; //Change this to Contact array, not string
//Contact c; //You can remove this line
//Rest of your code
}
public void add(String first, String last, String number)
{
//Only add if the number of contacts is less than the max
if (contactsAdded < MAX)
{
//Construct the new contact when you use it.
contacts[contactsAdded] = new Contact(first, last, number);
contactsAdded++;
}
}
Not sure if I understood all of your code right, but I think you are overwriting all other contacts in your phone book:
public void add(String first, String last, String number){
c=new Contact(first,last,number); //(1)
for(int i=0;i<MAX;i++){ //(2)
contracts[i]= c.toString();
}
}
At position (1) a new Contact object is created and assigned to c. In the next step (2), you loop through the array and assign the info contained in c (the latest contact added) to all already entries in the contracts array.
Independent from your problem, I suggest that you replace the array of a fixed size with i.e. an ArrayList of type Contact. Adding entries to this list, iterating, sorting etc is very easy.

How to remove chosen variable from array list?

This is a program which stores employee's information (salary, names, ID#, date hired) in an array list. When called upon (after pressing 'listButton') it lists this information in a Field for employer to look at. The employee needs to remove an employee from the list, there is a removeButton, so what would allow the employer to delete a name from the list of employees?
public class EmployeeView extends FrameView {
class Company {
String ID, firstName, lastName, annualSal, startDate, mileage;
Company (String _ID, String _firstName,String _lastName, String _annualSal, String _startDate) {
ID = _ID;
firstName = _firstName;
lastName = _lastName;
annualSal = _annualSal;
startDate = _startDate;
}
}
/** Define the ArrayList */
ArrayList <Company> employee = new ArrayList <Company>();
String ID, firstName, lastName, annualSal, startDate;
public EmployeeView(SingleFrameApplication app) {
//GUI stuff...
}
private void AddActionPerformed(java.awt.event.ActionEvent evt) {
ID = IDField.getText();
firstName = firstNameField.getText();
lastName = lastNameField.getText();
annualSal = annualSalField.getText();
startDate = startDateField.getText();
Company c = new Company(ID, firstName, lastName, annualSal, startDate);
employee.add(c);
}
private void ListActionPerformed(java.awt.event.ActionEvent evt) {
String temp = "";
for (int x=0; x<=employee.size()-1; x++) {
temp = temp + employee.get(x).ID + " "
+ employee.get(x).firstName + " "
+ employee.get(x).lastName + " "
+ employee.get(x).annualSal + " "
+ employee.get(x).startDate + "\n";
}
employeeTArea.setText(temp);
}
private void removeButtonActionPerformed(java.awt.event.ActionEvent evt) {
//My attempt... it didn't do anything though
int remove = 0;
for (int j = 0; j < employee.size()-1; j++) {
if (remove == Integer.parseInt(IDField.getText())) {
employee.remove(j);
}
}
}
You are initializing remove=0, what you want to do is:
for (int j = 0; j < employee.size()-1; j++) {
if (j == Integer.parseInt(IDField.getText())) {
employee.RemoveAt(j);
}
}
You don't need a remove variable. This is providing that IDField.getText() is the index of the employee you want to remove from the ArrayList
You can eliminate the for loop and just do employee.remove(company).

Categories

Resources