Reading a text file and separating it with delimiter - java

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?

Related

Java math operations on variable number of arguments

I'm new at starting object oriented programming. I have tried to find a topic that would answer my questions, but I haven't seem to find my answers yet. I hope I'll get help ^^
I am trying to understand something. I have the following class:
class Employee {
private String SIN ; // format "123 456 789", ex : "250 343 567"
private double salWeek ; // example 1075.25 $
. . . Constructors to write . . .
. . . Other methods to write . . .} // End of Employee class
I have to create the following constructors:
Employee emp1 = new Employee("321 498 726", 987.50); // 987.50$ is Total salary for week
Employee emp2 = new Employee("135 444 321", 45.00, 20.00); /* 45 hr x 20$/hr.
900.00 $ is Total salary for week*\
And I have to print informations on the second employee with the following method:
emp2.print("Informations of second employee");
to get
SIN: 135 444 321
Weekly Salary: 900.00$ per week
I am a bit confused since I have two entering arguments for the salary (45 and 20) on which I was thinking doing a math operation (45*20). I just don't seem to understand how to do it.
I then have to modify and print emp1 salary using emp2 salary and adding 123.25$ (giving a total of 1023.25$).
Is it possible to let me know how I could do it? I have code parts if needed.
Thank you!
Here is the code I have so far:
public class Employee {
private String SIN ;
private double salWeek;
public String getNAS() {
return NAS;
}
public double getsalWeek() { //Needs work since emp2 has 2 arguments
/*I was thinking here of adding math operation to get second and third argument and make multiplication if salary has 2 arguments*/
return salWeek;
}
public static void main(String[] args) {
Employee emp1 = new Employee("321 498 726", 987.50);
Employee emp2 = new Employee("135 444 321", 45.00, 20.00); //Weekly salary is 45 * 20
emp2.display("Informations on second employee");
System.out.printf("NAS: %s\n",emp2.getNAS());
System.out.printf("Weekly salary: %d\n",emp2.getsalWeek());
}
}
Edit: Clarification on variables + code part. Code part is NOT complete and needs work.
You can do it as follows:
printInfo(Employee e){
System.out.println("SIN : " + e.getSIN());
System.out.println("Weekly Salary : " + e.getSalHabdo()*e.getSecondSal());
}
Please note that the above method assumes that you have three fields in your class - SIN, salHebdo and the third one which you're setting in the second constructor.
edit-1 : Please provide the getter and setter code of your class and clarification on the third field you're setting using the constructor.

Creating and accessing Array data in 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.

Trying to compare rep sales in an array list in Java

Ok so here is my issue. I am trying to compare the annual sales of two or more sales reps in an ArrayList and am getting some strange results that I just can't figure out. I have to compare the two, then tell the user how much the rep with the lower sales needs to sell to take the lead. I have it broken into three classes. But I'm pretty sure this act is dependent on just two of those. The first is:
import java.util.ArrayList;
/**
*
* #author Cameron
*/
public class SalesRep {
private ArrayList<CompensationCalculator> pool;
public SalesRep(){
pool = new ArrayList<>();
}
public void setPool(ArrayList<CompensationCalculator> pool){
this.pool = pool;
}
public ArrayList<CompensationCalculator> getPool(){
return pool;
}
public void addToPool(CompensationCalculator salesRep){
pool.add(salesRep);
}
public String toString(String report){
double diff;
for(int i=0; i<pool.size(); i++){
if (pool.get(i).getSales() < pool.get(i++).getSales()){
diff = pool.get(i++).getSales() - pool.get(i).getSales();
report = pool.get(i).getName() + "needs to sell " +
diff + " to take the lead.";
}
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
}
return report;
}
}
That class should compare the two reps in the array while this one displays it to the user:
import java.util.Scanner;
public class AnnualSales {
public static void main(String[] args){
CompensationCalculator test = new CompensationCalculator(); //Creates a new instance of the class
SalesRep testName = new SalesRep(); //Creates a new instance of the SalesRep class
String cont = new String(); //A string to represent if there ar emore names to be added
Scanner scan = new Scanner(System.in); //Allows for user input to be read
while (!cont.equalsIgnoreCase("n")){
System.out.println("What is the name of the sales representative? ");
test.setName(scan.next());
System.out.println("Please enter " + test.getName() +
"'s annual sales: ");
test.setSales(scan.nextDouble());
testName.addToPool(test);
System.out.println("Are there any more sales representatives you "
+ "would like to add? ");
cont = scan.next();
}
System.out.print(testName.getPool());
System.out.print(testName.toString());
}
}
Now there are no errors being found, the program compiles and executes without a problem. But as a result I get
`[compensationcalculator.CompensationCalculator#55f96302, compensationcalculator.CompensationCalculator#55f96302]compensationcalculator.SalesRep#3d4eac69'
I am extremely confused and have been working on just this method for three hours so I am sure I need a fresh pair of eyes. Any help or guidance would be amazing.
EDIT:
Ok so your suggestion to use a Comparator was deffinetely helpful. I was also confusing myself with unnecessary code so I reworked it a bit and now it is working except for one aspect. Here is the code that I changed:
public String compare(SalesRep rep1, SalesRep rep2){
NumberFormat fmt = NumberFormat.getCurrencyInstance();
Double diff;
if (rep1.getSales() > rep2.getSales()){
diff = rep1.getSales() - rep2.getSales();
return rep2.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
else{
diff = rep2.getSales() - rep1.getSales();
return rep1.getName() + " needs to sell " + fmt.format(diff) +
" to take the lead.";}
}
I also renamed my classes to better organize them to account for the new requirements. Now the only problem is that it is giving a difference of the two sales as $0.0 no madder what I input. Am I calling on each objects sales incorrectly? I feel like I have run into this problem before but reviewing my past code isn't highlighting what I am doing wrong.
I don't see you call toString(String) but only toString(), that's why you'd get that "stange" output.
Btw, that report parameter of your toString(String) method seems quite odd, since you're not using it besides assignments. You should use a local variable in that case.
Another potential error:
if (pool.get(i).getSales() > pool.get(i++).getSales()){
diff = pool.get(i).getSales() - pool.get(i++).getSales();
report = pool.get(i++).getName() + "needs to sell " +
diff + " to take the lead.";
}
Here you are incrementing i three times, so you'd refer to 3 different indices in pool.
Suppose i = 0, then you'd get:
//the first i++ returns i (0) and then increments i to 1
if (pool.get(0).getSales() > pool.get(0).getSales()){
//here i is 1, thus the next i++ returns 1 and increments i to 2
diff = pool.get(1).getSales() - pool.get(1).getSales();
//here i is 2, so the next i++ returns 2 and increments i to 3
report = pool.get(2).getName() + "needs to sell " +
diff + " to take the lead.";
}
So in that second case you'd add 3 to i and thus advance the loop by 4, since the i++ in the loop's head also increments i once more. I'd suggest you use i + 1 in your loop body instead of i++.
Besides that, your design is quite odd, since class CompensationCalculator actually seems to define a sales rep.
Another thing: I'd probably sort the list of sales reps in descending order (hint: use a Comparator). Then element 0 would be the sales rep with the highest sales and the last element would be the sales rep with the lowest sales. Difference calculations would then be a piece of cake.
The toString that you are calling is the method inherited from Object. The toString method that you defined takes a String parameter.
System.out.print(testName.toString());
so override the proper method.
or use the returned String from your method.
String out;
out = testName.toString(out); // Strings are immutable
Add #override annotation to your toString method and move report in, lie so:
#Override
public String toString(){
String report;
.....
}

How to get started on this project? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm struggling to understand the instructions for my project, english is my second language so can someone help break it down and assist me in how i would go about this project?
Project Summary
Write a program that produces statistics for a baseball team.
Instructions:
Create the BaseballStats class:
It has two instance variables:
teamName, a String
battingAverages, an arrays of doubles representing the batting averages of all the players on the team.
The class has the following API:
Constructor:
public BaseballStats( String filename )
The team name and the batting averages for the team are stored in the file. You can assume the first item in the file is the team name (one word – no spaces), followed by exactly 20 batting averages. Your constructor should read the file into the teamName instance variable and the battingAverages array.
Methods:
public String getTeamName( )
accessor for teamName
public void setTeamName( String newTeamName )
mutator for teamName
public double maxAverage( )
returns the highest batting average
public double minAverage( )
returns the lowest batting average
public double spread( )
returns the difference between the highest and lowest batting averages
public int goodPlayers( )
returns the number of players with an average higher than .300
public String toString( )
returns a String containing the team name followed by all the batting averages formatted to three decimal places.
Client class:
Your client should instantiate an object of the BaseballStats class, passing the name of the text file containing the team name and the averages. The client should then call all methods, reporting the results as output.
It seems you've perhaps never used Java before judging by your comment. Here is how it should be laid out:
class BaseballStats {
private String filename;
public BaseballStats ( String filename )
{
this.filename = filename;
}
public String getTeamName( )
{
//accessor for teamName
}
public void setTeamName( String newTeamName )
{
//mutator for teamName
}
public double maxAverage( )
{
//returns the highest batting average
}
public double minAverage( )
{
//returns the lowest batting average
}
public double spread( )
{
//returns the difference between the highest and lowest batting averages
}
public int goodPlayers( )
{
//returns the number of players with an average higher than .300
}
public String toString( )
{
//returns a String containing the team name followed by all the batting averages formatted to three decimal places.
}
}
Your client (a different java file in the same directory) can create an instance of this class with:
BaseballStats newTeam = new BaseballStats(filename);

Abstract Concept Assignment [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
So my questions are geared directly to my homework. Before you ask, yes I've looked at other questions and I have looked at the java docs to try and help me but I only understand so much..
You have become a restaurant mogul. You own several fast food chains. However, you now need to set a standard that all of your fast food chain must follow in order to have your software be uniform across the board. There will be some rules that will be the same for all restaurants.
Create an Abstract Class named Restaurant
Create a function/method that will print the name of the restaurant when called.
Create an abstract function/method named total price
Create an abstract function/method named menu items
Create an abstract function/method name location
Create a Class called McDonalds that extends Restaurant
Implement all abstract methods
Add logic so that the total price method/function will give the total price of the meal including a 6% tax
Add a method that returns a Boolean named hasPlayPlace. Which returns true when this location has a playplace
Create a Constructor that will set the name of the Mcdonalds, location, and hasPlayPlace
public class McDonalds extends Restaurant {
private String name;
private String location;
private boolean hasPlayPlace;
Scanner input = new Scanner(System.in);
public McDonalds (String name, String location, boolean hasPlayPlace) {
setName(name);
setLocation(location);
setHasPlayPlace(hasPlayPlace);
}
McDonalds location1 = new McDonalds("McDonalds", "Kirkman", false);
McDonalds location2 = new McDonalds("McDonalds 2", "International Dr.", true);
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLocation() {
return location;
}
public void setLocation(String location){
this.location = location;
}
public boolean isHasPlayPlace() {
return hasPlayPlace;
}
public void setHasPlayPlace(boolean hasPlayPlace) {
this.hasPlayPlace = hasPlayPlace;
}
public void totalPrice() {
double totalPrice = 0;
double tax = 0.06;
totalPrice += (totalPrice * tax);
}
public void menuItems() {
//some syntax is wrong in this method
double mcChicken = 1;
double fries = 1.25;
System.out.println("1. Mc Chicken $1");
System.out.println("2. Fries $1.25");
int choice = input.nextInt();
switch (choice){
case 1: mcChicken *= tax;
case 2: fries *= tax;
}
}
public void location() {
//Don't know what's supposed to go in here.
//But I've implemented the method as I was supposed to.
}
}
Does it all make sense is basically what i'm asking.
What should go in the location method?
What's the use of getters and setters within this class and did I do it right?
1) Your constructor is structured fine, but you should use Strings instead of chars for the name and location. A char will only hold one character.
2) You can create multiple instances of a class:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
McDonalds location2 = new McDonalds("McDonald2", "Kirkman", false);
3) You should add the tax to the price as a percentage, not a sum: price * 1.06. Be careful not to change the price w/o tax when you print the total price.
Name and location should be String not char.
I like the style of calling setters from within the constructor, because its a form of code reuse, especially if there are special checks being made on those values, such as not being null - calling he setter means you only check this in one place.
Your code won't compile, but you're close:
McDonalds location1 = new McDonalds("Some name", "Kirkman", true);
Your calculation is a little off too:
double tax = 0.06;
totalPrice *= (tax + 1);
However, this is dangerous because if called twice, it will add the tax twice. It would be better to have a method return the tax included price which calculates it every time. Having a getter with side effects is a design error. Ie have thus:
public double getTaxIncPrice() {
double tax = 0.06;
return totalPrice * (1 + tax);
}
In addition to the problem that Bohemian pointed out (name and location should be String, not char):
Your constructor call will need quotes on the String parameters:
McDonalds location1 = new McDonalds("McDonald", "Kirkman", true);
and your tax calculation is incorrect - you will need to multiply the total amount by the tax percentage, and you will have to wait until you actually have a total to do the calculation.
Just editted my code and provided the question. Your guys inputs helped so far.
public String TacoBellSauce(String fire, String hot, String mild) {
System.out.println("What sauce would you like to have?");
System.out.println("1. Fire");
System.out.println("2. Hot");
System.out.println("3. Mild");
int choice = input.nextInt();
switch(choice) {
case 1:
return fire;
case 2:
return hot;
case 3:
return mild;
}
return null;
}
Here is also my method for the TacoBell class. How would I return it in the Test class? It says to make a method within TacoBell that returns a string of what hot sauce I would like. But then it says within the test class to call hotsauce and return hot. I haven't created that class yet cause I'm focused on correcting everything with McDonalds and TacoBell.

Categories

Resources