Creating and accessing Array data in Java - java

I have a a textbook question that I have attempted many times and still does not work here are the instructions:"
Write a Payroll class that uses the following arrays as fields:
employeeId. An array of seven integers to hold employee identification numbers. The array should be initialized with the following numbers:
5658845 4520125 7895122 8777541 8451277 1302850 7580489
hours . An array of seven integers to hold the number of hours worked by each employee
payRate . An array of seven double s to hold each employee’s hourly pay rate
wages . An array of seven double s to hold each employee’s gross wages
The class should relate the data in each array through the subscripts. For example, the number in element 0 of the hours array should be the number of hours worked by the employee whose identification number is stored in element 0 of the employeeId array. That same employee’s pay rate should be stored in element 0 of the payRate array.
In addition to the appropriate accessor and mutator methods, the class should have a method that accepts an employee’s identification number as an argument and returns the gross pay for that employee.
Demonstrate the class in a complete program that displays each employee number and asks the user to enter that employee’s hours and pay rate. It should then display each employee’s identification number and gross wages.
Input Validation: Do not accept negative values for hours or numbers less than 6.00 for pay rate."
so far I have my main class:
public class Payroll {
public static void main(String[] args){
Pay work = new Pay();
Scanner input = new Scanner(System.in);
int[] hours = new hours[work.getLength()];
for (int i=0; i<work.getLength(); ++i) {
System.out.println("How many hours has Employee #"+work.getEmployeeId(i)+" worked?");
input.nextInt() = hours[i];
while (hours[i]<6){
System.out.println("Error, inadequit value!");
System.out.println("How many hours has Employee #"+work.getEmployeeId(i)+" worked?");
input.nextInt() = hours[i];
}
}
}
I also have a class named Pay:
public class Pay {
private int[] employeeId;
//private int[] hours = new hours[employeeId.length];
//private int[] pay = new pay[employeeId.length];
//private int[] wage = new wage[employeeId.length];
public Pay() {
employeeId = new int[]{5658845, 4520125, 7895122, 8777541, 8451277, 1302850, 7580489};
}
public int getLength(){
return employeeId.length;
}
public int[] getEmployeeId(int id) {
return employeeId[id];
}
I'm just not sur where to go next after all of this. Please help.

I am going to answer this for the simplest way instead of the proper way, since I'm assuming you are somewhat new to programming. This is based on the fact that there seems to be no emphasis on class or any real modularization.
You just want to have 4 arrays of size 7.
The employee ids array will be set by you.
As you prompt the user for the information you save it in the correct array based on the index of the employee being set.
The method for gross pay would just take the id number of the employee, find their index number in the arrays and get the information necessary to calculate and return the gross pay. (presumably gross pay is wageRate * hoursWorked)
This is the simplest way of doing it, separate classes aren't necessary.

A better way of doing this, on object-oriented principles, will be to avoid using multiple arrays. Instead create a class that holds all the employee attributes together, as an object.
public class Employee {
private int id;
private int hours;
private double rate;
// constructors
// it should not have arguments such as id, hours or rate
// because it is a method of this class and those attributes are
// implicitly assumed.
public double getWage() {
return hours * rate;
}
// toString method
#Override
public String toString() {
return "Employee ID = " + id + "," + "hours = " .....
}
}
Wage can be pre-calculated and stored as another field at the time of construction. Or calculated at the time of request as is done above.
The Payroll class:
public class Payroll {
private Employee[] employees;
private int lastIndex = 0;
// constructors
// for example, one constructor can accept initial size
public Payroll(int size) {
employees = new Employee[7];
};
public addEmployee(Employee employee) {
// need to check overflow before attempting to add
// add employee
employees [lastIndex ] = emplyee;
lastIndex++;
}
// more methods, such remove etc
}
Now the driver, or application class
public class Driver {
public static void main(String[] args){
Payroll payroll = new Payroll (7);
// code to pupulate the Payroll with values
for ( ) {
// construct new Emplyee object
// add object to Payroll
}
// Printing
for (Emplyee e: Payroll) {
System.out.println(e.toString());
}
}
}
Note that the application or driver class is separated from the Payroll, now each class does one thing, and only that thing. Remember that it is not the concern of Payroll class to populate itself or print its content etc.

Related

How to make calculation inside class field in Java?

So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");

Reading a text file and separating it with delimiter

I am kinda stuck on the following problem and need some guidance. I am trying to read a text file and separate it within a program that I already wrote. The text file will look as follows.
2014 Employee lock,John 3000
2015 Salesman Manning,Bill 4000 50000
2014 Executive Zuck,George 2000 55
I know that I can created a array of objects such as:
Employee[] employee2014 = new Employee[10];
Employee[] employee2015 = new Employee[10];
I am unsure how to use a delimiter to separate the different years and then store the employee information into those years in order. I already wrote three classes for (Employee is parent class to salesman and executive) the program but just need the guidance on the delimiter to store the information in the object. also I don't want to use a array list because my text file only has a limit of 10 items.
Here is an example of one the sub classes Saleman. The parent class Employee and other subclass Executive have the same methods and toString, so I will not post them.
public class Salesman extends Employee {
protected double annualSales;
public Salesman(int monthlySalary, String name, double annualSales)
{
super(monthlySalary, name);
this.annualSales = annualSales;
}
#Override
double annualSalary() {
double commission = .02;
commission = commission * annualSales;
if(commission > 20000)
{
commission = 20000;
}
return (super.annualSalary() + commission);
}
#Override
public String toString() {
return (super.toString() + "\nAnnual Sales: " + annualSales);
}
}
I will be using a filreader and bufferedreader to read the file, but how will I use a delimiter to separate into the class objects to be read by the years?

How to use integers inside of an array as parameters for a method. (Tester)

I calculate an integer and assign it into an array using a method inside a for loop, then the next method in that for loop needs the previous integer calculated as a parameter I declared it as an double which fixed that problem but now I need to print the result and I have the same problem, what do i put in the method parameters when printing because the variable was wiped after every loop in the first loop.
This is the main method class :
public class AnnualFuelTester {
public static void main(String args[]) {
//declaration of variables
int endMiles, startMiles;
double gallonsUsed, pricePerGallon;
//initialization of an array of objects
AnnualFuelUse[] fillUps = {
new AnnualFuelUse(45023, 45231, 10.00, 2.95),
new AnnualFuelUse(45231, 45480, 11.70, 2.99),
new AnnualFuelUse(45480, 45659, 9.30, 3.03),
new AnnualFuelUse(45659, 45961, 14.90, 3.05)
};
//call methods
for (int index = 0; index < fillUps.length; index++) {
double distance = fillUps[index].calcDistance();
fillUps[index].calcMPG(distance);
fillUps[index].getStartMiles();
fillUps[index].getEndMiles();
fillUps[index].getGallons();
fillUps[index].totalCost(distance);
}
//print results
System.out.printf(" %15s %15s %15s %15s %15s %15s %15s %15s %15s", "Fill Up", "Days", "Start Miles", "End Miles", "Distance", "Gallons", "Miles/Gal", "Gallons/Miles", "Price", "Total Cost\n");
for (int index = 0; index < fillUps.length; index++) {
System.out.printf("%15i %15i %15s %15s %15d %15d %15d %15d %15d", index, index, fillUps[index].getStartMiles(), fillUps[index].getEndMiles(), fillUps[index].calcDistance(), fillUps[index].getGallons(), fillUps[index].calcMPG(distance), fillUps[index].totalCost(distance), "\n");
}
}
}
This is the Class with the methods:
public class AnnualFuelUse {
//private instance variables
private int myEndMiles, myStartMiles;
private double myGallonsUsed, myPricePerGallon;
AnnualFuelUse(int sm, int em, double gu, double ppg) {
myEndMiles = em;
myStartMiles = sm;
myGallonsUsed = gu;
myPricePerGallon = ppg;
}
//distance driven
public double calcDistance() {
return myEndMiles - myStartMiles;
}
//calculate miles per gallon
public double calcMPG(double distance) {
return distance / myGallonsUsed;
}
//calculate gallons per mile
public double calcGPM(double distance) {
return (distance / myGallonsUsed) / 100;
}
//calculate total cost
public double totalCost(double distance) {
return myPricePerGallon * distance;
}
//getter start miles
public int getStartMiles() {
return myStartMiles;
}
//getter end miles
public int getEndMiles() {
return myEndMiles;
}
//getter gallons used
public double getGallons() {
return myGallonsUsed;
}
//getter price per gallon
public double getPricePerGallon() {
return myPricePerGallon;
}
}
The instructions for this program are
If you have not yet created the 8.08 Annual Fuel Use project in the Mod08
Assignments folder, please do so now.
Be sure to save a copy of these instructions in the Mod08 Documents folder.
Print a copy for your notebook.
Read the instructions carefully before you attempt the assignment.
Create two classes called
AnnualFuelUseTester and AnnualFuelUse
in the newly created project folder.
Use the fill up data you have been collecting
for your car (or the family car) and calculate
the total distance, gallons used, and cost of
gas.
Determine the minimum and maximum
values for distance, miles per gallon and
price. (Recall the Integer class constancies
MIN_VALUE and MAX_VALUE. The
Double class also has class constants of the
same name.)
Calculate annual projections for distance,
gallons used, miles per gallon, and cost
based on the data you collected.
Each fill up should be considered an object and your program design should be
based on an array of objects. Use the demo program in this lesson as a model for
how to create and process an array of objects.
If you are basically expecting the value calculated in .calcDistance() method, Have your method .calcDistance() return a value (the one you require).
Store it in a variable or directly pass that to the second called function .clacMPG()
As you are already returning a value from .calcDistance() you can do something like
int dist = fillUps[index].calcDistance();
and now you can use this dist value in any other method calls you make, like
fillUps[index].calcMPG(dist);
you can basically use one variable which will get overwritten every time the loop runs.
Use another variable:
int dist=fillUps[index].calcDistance();
//or double, depands on the method's returning value
fillUps[index].calcMPG(dist);
Assuming that AnnualFuelUse constructor arguments are: start miles (odometer), end miles, gallonsUsed and pricePerGallon.
One way to do this is returning the distance and passing as argument to the next:
int distance = fillUps[index].calcDistance();
fillUps[index].calcMPG(distance);
I can't see in your code how you are consolidating data and how you're projecting future data.
**Ok. Based on your "edit", now I know that you don't have a question, You want someone to do your homework for you!!! **

Accessing user created variables for an array in a separate class Java (for homework)

I am super new to Java (4 days) and have never really coded anything except SQL databases and some simple java script before. I am building a sales commission calculator with a special policy that adjusts the amount of commission made based on an annual sales amount tier system (<=96,000, >96,000<=120,000 and >120,000).
I have that completed. . .What I need now is a way to use a second class(a second class is required ) to create an array that takes the output or input to/from the user and shows the user the potential money he/she could have made if his or her sales were at "X" in increments of 5,000 up to 50% of the user input for total sales. Here is the code I have so far: (I know my SystemOutTest class was in bad form sorry)
/**
*
* #author Wudkong
*/
import java.util.Scanner;
public class SystemOutTest {
Potentialwagechart Potentialwagechart;
public SystemOutTest(Potentialwagechart Potentialwagechart) {
this.Potentialwagechart = Potentialwagechart;
}
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
// main method for mathematics
Scanner input; // determines the method for the scanner
input = new Scanner(System.in); // creates an instance of scanner
int salary; // creates variables to be used later
int totalSales;
double commissionPercent;
double totalPay;
double commission;
salary = 50000; // defines a variable to a specific value for annual
// salary
System.out.print("enter annual sales amount please: ");
/**
* asks the user for the amount sold for the year
*/
totalSales = input.nextInt();
/**
* creates dialogue box for user to enter the annual sales amount
*/
commissionPercent = .15; // defines received total from sales data
if (totalSales <= 120000 * .8) {
commissionPercent = 0;
} else if (totalSales > 120000) {
commissionPercent = .1875;
;
} else
commissionPercent = .15;
{
commission = totalSales * commissionPercent;
/**
* Uses user defined data and commission percentage to create a
* value for total commission amount
*/
totalPay = commission + salary; // adds totals together
System.out.printf("Total annual pay is %.2f ", totalPay);
/**
* this uses an output stream to report to the user of the result of
* the method with just two decimal places showing.
*/
}
}
}
I would like to start the next class here but I am willing to take advice on just about anything. I know my code is sloppy and I do not know the best way to do this next part. I think I can build an array from a constant object just not an object that needs to be acquired from the user first. I also do not know how to make my classes communicate in the best way. I tried creating a reference to my second class in my first class and vice-versa but without the array or the object reference in place I can't test those links. Any help here is appreciated! I don't know if a get/set method can work or if I need to reference the output instead of the user input to create the array output plus 5,000 and the new potential wage on the side for x spaces. . ?

Scanner and String Comparison

I have the following text in a file :
3
apple 4 1.00
chicken 1 3.25
cookie 38 0.25
avocado 1 4.00
blueberries 1 5.00
chicken 2 3.25
milk 9 4.50
tomato 27 0.50
chicken 2 3.25
I want to list each item and its number and its price but I want that if I encounter the same item again to add its number to the existing number I have
I figured out the first part but I can't get the second any one has any ideas ?
public static void main(String[] args) throws FileNotFoundException{
Scanner sc = new Scanner(new File("Groceries.txt"));
while(sc.hasNext()) {
String line=sc.nextLine();
Scanner ss = new Scanner(line);
if(ss.hasNextInt()) {
ss.next();
}
while(ss.hasNext()) {
String name=ss.next();
int number = readInt(ss);
double price = ss.nextDouble();
System.out.printf("The item is %s its number is %d and its price is %.1f\n",name,number,price);
}
}
}
public static int readInt(Scanner sc) {
while(!sc.hasNextInt()) {
sc.hasNext();
}
return sc.nextInt();
}
Create a container object like so:
public class Container
{
private String item;
private double cost;
...
}
Use a HashMap<Container, Double> as your data structure. Every time you come across a duplicate, update its value.
If there is a possibility for an arbitrary amount of repeats, you can use do the following:
public class ValueContainer
{
private int count;
private double value;
}
and have a HashMap<Container, ValueContainer>, and update accordingly. There seems to be some confusion between what you say in the question and in a comment. Regardless, with simple substitutions, this construct will get you to where you want to go.
Create a class describing the attributes of your item (name, price, quantity , count etc).
Create a list of items (Yes, use generics..) // u can also use a map instead of a list..
Now, with each line you read from the text file, first get the item name using split().
Check if the item is already present. If yes, take it out, increment its count and put it back. if No, then add a new item to the list.
Happy Coding...

Categories

Resources