How to get started on this project? [closed] - java

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);

Related

trying to get an int and a double from my main method to a non-static method [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I'm working on a project for school and I've run into a wall where I need to get a user inputted Int and double from my main method to a required non-static method. this non-static method is supposed to be used for the calculation and printing of the answer based on the price (double) and the amount paid (int).
public static void main (String[] args){
Scanner check = new Scanner(System.in);// import of the scanner
char cents = '\u00a2';//Unicode of cent symbol
System.out.print("Your item costs (25" + cents + " minimum, Increments of 5" + cents + "): ");
Double price = check.nextDouble(); //price of the item
System.out.println("You paid (whole dollars only): ");
int paid = check.nextInt(); //amount paid
VendingChange newVend = new VendingChange();//creates a copy of the class
newVend.Secondary();// calls the nonstatic
that's the main method
public void Secondary () {
System.out.println("your change is " +/*this is where the equation is supposed to go*/ );
and this is the non-static
I've tried adding an extra static method, which eliminated the errors, but the int and double still wouldn't go through. meaning I can't use the int and double in any other method, because it doesn't recognize the names.
try replacing
Double price = check.nextDouble();
with
double price = check.nextDouble();
or even
String price1 = check.nextLine(); // gets input in form of string
double price = Double.parseInt(price1); // converts to double
Similarly, integers can also be changed:
int paid = check.nextInt();
to
String paid1 = check.nextLine();
int paid = Integer.parseInt(paid1);
I would also recommend reading (as mentioned in the comments) tutorials and really understanding the difference with static and non-static methods (instance).
(uppercase represents the class, while lowercase represents an instance)
Let's say we have a Person class. A static method would be like
Person.getPopulation(). That would return the population. This method is not instance (person) specific, rather it applies to the type of thing a person is.
An instance method would be better when you have something like person.changeName(). This would change the name of a person. An instance of a person. However, if you create it static, like Person.changeName(), which person's name would you be changing?
Think of the class Person like a type of object. People are objects (in this analogy). Person class is a type. Every person instance is every person that lives (in the program).
This same 'type of thing' vs actual 'thing' that exists under that type can be applied to a lot of things in programming, and is the basis of Object Oriented Programming (OOP).

Cannot find the logical error in the stated program regarding classes and objects [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I need to design Employee class in such a way so that the following code prints 12000; There are no run-time erros, it's a logical error that I made and cannot identify.
This is the java code
class Employeetester{
public static void main(String[] args){
Employee a=new Employee();
a.name="Mohammad Java Chowdhury";
a.salary=10000;
a.increaseSalary(20.0); //percentage
System.out.println(a.salary);
}
}
This is the class file where I declared the method.
public class Employee{
String name;
double salary;
double exchange;
public double increaseSalary(double salary){
salary=salary+(salary*(20.0/100.0));
return salary;
}
}
The Output is showing 10000.
I am very new to this topic, sorry for any inconvenience
Use the proper name for the parameters of your method. Also, a simpler algorithm:
double increaseSalary( double pct ) {
return salary * ( 1. + (pct/100.) );
}
Another way to increase salary by 20% would be to divide current salary by 100, which will give you 1% and multiply that by the percentage you want to increase salary by. So something like this:
salary = salary + (salary / 100.0) * percentage.
Where percentage is 20 in your case.
Also, you have to distinguish salary as a method parameter and a class field. Either use this keyword to refer to a class field, or change the name of the method parameter:
public double increaseSalary(double salaryArg){
salary=salaryArg+(salaryArg*(20.0/100.0));
return salary;
}

Sort Objects From a File [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
(At time of posting, I do not have access to code, will add later)
I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.
When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.
This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.
So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you
static void employeeSort(Employee[] emply, int size)
{
int i;
Employee temp;
boolean flag = true;
while(flag)
{
flag = false;
for(i = 0; i < size; i++)
{
if (emply[i].getName().compareTo(emply[i+1].getName())>0)
{
System.out.println(emply[i].getName());
temp = emply[i];
emply[i] = emply[i+1];
emply[i+1] = temp;
flag = true;
}
}
}
}
On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.
public class Employee implements Serializable
{
int prefHours;
String name;
String avail;
Employee( String nam, int hours, String aval )
{
name = nam;
prefHours = hours;
avail = aval;
}
void prnEmpl()
{
System.out.print("Name: " + name);
System.out.println();
System.out.print("Prefered hours: " + prefHours);
System.out.println();
System.out.print("Availability: " + avail);
System.out.println();
}
String getName()
{
return name;
}
String getAvail()
{
return avail;
}
}
Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.

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.

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?

Categories

Resources