Java – how do I modify this program to use ArrayList?

First, the following is a description:

As far as the code is concerned, I have completed all the contents required for the user to enter all the input parts However, I need help to "transfer" data from the class to the 'ArrayList' we should use I think once I figure it out, I will be able to sort the array to find the ID number that selects "B". If the user enters "C", I will only cycle through the array of all its contents

In any case, on the code (this is the main):

/*
 * Name:
 * Date:
 * Assignment 2
 */

import java.util.Scanner;

public class homework 
{
    public static void main(String[] args)
    {
        char userSelection;
        String convertString;
        String userStrings;
        Scanner kbd = new Scanner(system.in);

        do 
        {
            System.out.println("Here are your choices:");
            System.out.println("A. Enter employee data" +
                             "\nB. Search for employee data" +
                             "\nC. List all data" +
                             "\nD. Exit");

            convertString = kbd.next();
            userSelection = convertString.charAt(0);

            switch(userSelection)
            {
            case 'A':
                GetUserInfo();
                break;
            case 'B':
                // Stuff;
                break;
            case 'C':
                // Display all data;
                break;
            case 'D':
                System.out.println("Goodbye!");
                break;
            default:
                System.out.println("Error,that is not a valid entry. Please try again.");
            }
        } while (userSelection > 'D');
    }

    // Write functions here
    public static void GetUserInfo()
    {
        String firstName;
        String lastName;
        String empID;
        double hourlyRate;
        int hoursWorked;
        double withPercent;

        Scanner kbd = new Scanner(system.in);

        System.out.println("What is your first name?");
        firstName = kbd.next();

        System.out.println("What is your last name?");
        lastName = kbd.next();

        System.out.println("What is your employee ID?");
        empID = kbd.next();

        Employee user = new Employee(empID);

        user.setFirstName(firstName);
        user.setLastName(lastName);

        System.out.println("What is your hourly rate?");
        hourlyRate = kbd.nextDouble();

        System.out.println("How many hours did you work?");
        hoursWorked = kbd.nextInt();

        System.out.println("What is your withholding percentage?");
        withPercent = kbd.nextDouble();

        Pay user1 = new Pay();

        user1.setHourlyRate(hourlyRate);
        user1.setHoursWorked(hoursWorked);
        user1.setWithPercent(withPercent);
    }
}

This is the Employee class:

public class Employee 
{
    // Members of the class
    String firstName;
    String lastName;
    String employeeID;
    // remember about the pay object

    // EmployeeID constructor
    public Employee(String empID)
    {
        this.employeeID = empID;
    }

    // Below are the varIoUs getters and setters of the Employee class
    public String getFirstName() 
    {
        return firstName;
    }

    public void setFirstName(String firstName) 
    {
        this.firstName = firstName;
    }

    public String getLastName() 
    {
        return lastName;
    }

    public void setLastName(String lastName) 
    {
        this.lastName = lastName;
    }

    public String getEmployeeID() 
    {
        return employeeID;
    }

}

This is the pay class:

public class Pay 
{
    // Members of the class
    double hourlyRate;
    int hoursWorked;
    double withPercent;

    // VarIoUs getters and setters of the Pay class
    public double getHourlyRate() 
    {
        return hourlyRate;
    }

    public void setHourlyRate(double hourlyRate)
    {
        this.hourlyRate = hourlyRate;
    }

    public int getHoursWorked() 
    {
        return hoursWorked;
    }

    public void setHoursWorked(int hoursWorked) 
    {
        this.hoursWorked = hoursWorked;
    }

    public double getWithPercent() 
    {
        return withPercent;
    }

    public void setWithPercent(double withPercent)
    {
        this.withPercent = withPercent;
    }   

    // Calculates the raw payment
    public double CalcPayRate(double hourlyRate,int hoursWorked)
    {
        return hourlyRate * hoursWorked;
    }

    // If the employee has worked overtime,calculates the new payment
    public double CalcOvertimePay(double hourlyRate,int hoursWorked)
    {
        double rawPay = 0;

        rawPay = hourlyRate * hoursWorked;

        if (hoursWorked > 40)
        {
            rawPay *= 1.5;
        }

        return rawPay;
    }

    // Calculates final amount that the employee will be paid
    public double CalcTotalPay(double hourlyRate,int hoursWorked,double withPercent)
    {
        double rawPay = 0;
        double subTotalPay = 0;
        double finalPay = 0;

        rawPay = hourlyRate * hoursWorked;
        subTotalPay = rawPay * withPercent;
        finalPay = rawPay - subTotalPay;

        return finalPay;
    }
}

Well, may I ask? Final comments: (1) I don't understand what 'pay object' should be done under the Employee class? (2) How do I use the input data to create a "payment object" and then create an employee object? These are two parts of the description I don't know very well, so if you can understand it, it will help! (3) If there is any similarity in my grammar, please let me know so that I can change it accordingly I'm still new to the language, so any help would be great

Editor: I have updated my code with comments:

public class homework 
{
    public static void main(String[] args)
    {
        // ArrayList<Employee> employeeList = new ArrayList<Employee>();

        do 
        {
            // Stuff commented out for readability

            case 'A':
                PromptForinput();
                // Employee emp = PromptForinput();
                // employeeList.add(emp);
                break;
            } while (userSelection > 'D');
    }

    // public static Employee Promptinput()
    public static void PromptForinput()
    {           
        Employee user = new Employee(empID);

        // Isn't this supposed to be returned as well?          
        Pay user1 = new Pay();

        user1.setHourlyRate(hourlyRate);
        user1.setHoursWorked(hoursWorked);
        user1.setWithPercent(withPercent);

        //return user;
    }
}

What does it think? I still don't understand the 'paying object' part of the homework

Solution

First, let's look at collections

If I do

I will return employee from the getUserInfo method and add it to the ArrayList in the calling method This allows the getUserInfo method to focus on a single responsibility

I also allow getUserInfo to return null if the value entered by the user fails validation, but this may be outside the required range

For example

List<Employee> employees = // create ArrayList...
//...

Employee emp = getUserInfo();
if (emp != null) {
    employees.add(emp);
}

You should also set the pay object for the pay object when it is created, which associates the pay object with the employee so that you can find it later

As for your pay object Calcpayrate, calcovertimepay and calctotalpay do not require parameters, because all the information required by these methods should be obtained from the properties of the object

For example

public double getRawPay() {
    return getHoursWorked() & getHourlyRate();
}

I also encourage you to check out code conventions for the Java programming language

Updated #1

Associating a pay object with an employee is no different from how you associate things like employee names

Basically, you need to provide an instance field / property to save the reference, and provide some methods to set and get the reference, such as

public class Employee 
{
    //...
    Pay pay;

    // EmployeeID constructor
    public Employee(String empID)
    {
        this.employeeID = empID;
    }

    // EmployeeID constructor
    public Employee(String empID,Pay pay)
    {
        this(empID);
        this.pay = pay;
    }

    public void setPay(Pay pay) {
        this.pay = pay;
    }

    public Pay getPay() {
        return pay
    }
    //...
}

I provide a second constructor. You really don't need it, but it's a demonstration of how to implement it

Then you just pass the pay reference to the employee

Employee emp = new Employee(...);
//...
Pay pay = new Pay();
//...
emp.setPay(pay);

Update #2

Another way is to create a pay instance when creating an employee

public class Employee 
{
    //...
    Pay pay = new Pay();

    // EmployeeID constructor
    public Employee(String empID)
    {
        this.employeeID = empID;
    }

This shows that we no longer need setpay, but it's up to you

When you need to get or set the value of pay, you can simply ask the employee instance

Employee emp = ...;
emp.getPay().setHourlyRate(hourlyRate);
//...
double hourlyRate = emp.getPay().getHourlyRate();

Updated #3

Basically, you need to associate the pay instance with the employee instance If it's easier, name it other

Based on the example in update #1

public static Employee PromptForinput()
{
    String firstName;
    String lastName;
    String empID;
    double hourlyRate;
    int hoursWorked;
    double withPercent;

    //...
    Employee user = new Employee(empID);

    user.setFirstName(firstName);
    user.setLastName(lastName);

    //...

    Pay payObj = new Pay();

    payObj .setHourlyRate(hourlyRate);
    payObj .setHoursWorked(hoursWorked);
    payObj .setWithPercent(withPercent);

    // Don't forget to give an instance of Pay to the instance
    // of Employee
    user.setPay(payObj);

    return user;
}

Think of employee as a container that contains the name and ID of employees and their salary details When you start using the new employee instance, it is just an empty container. You need to fill it

When you need it, you only need to request and pay instances from employees through getPay

Update #4

Based on your new code, I will only make a small suggestion

In your display all data selection, you can use the following cycle to display employees and employee wage rates, for example

for (int i = 0; i < employeeList.size(); i++)
{
    Employee emp = employeeList.get(i);
    System.out.println(emp);
    System.out.println(emp.getPay().CalcPayRate());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>