For some reason when I input values for RTH and CTH I receive 0.0 values. I had a similar issue on my shift getters, but I managed to fix that. Unfortunately, attempting to reverse engineer the problem hasn't helped. I've provided the code for my class and my driver, although I am almost convinced the issue is somewhere in the class. Nevertheless, can anyone take a quick look at the RTH / CTH setters/ getters and see what I've done wrong in setting or calling them.
public class TeamLeader extends ProductionWorker
{
//private variables
private double RTH;
private double CTH;
private double payRate;
private double monthlyBonus;
//constructor
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
}
public void setmonthlyBonus(double monthlyBonus)
{
this.monthlyBonus = monthlyBonus;
}
public void setpayRate(double payRate)
{
this.payRate = payRate;
}
public void setRTH(double r)
{
RTH = r;
}
public void setCTH(double c)
{
CTH = c;
}
//Getters
public double getmonthlyBonus()
{
return monthlyBonus;
}
public double getpayRate()
{
return payRate;
}
public double getRTH()
{
return RTH;
}
public double getCTH()
{
return CTH;
}
}
Driver
public class WorkDriver {
public static void main(String[] args) {
String name;
String number;
String hireDate;
int shift;
double payRate;
double monthlyBonus;
double RTH;
double CTH;
name = JOptionPane.showInputDialog("Enter your name");
number = JOptionPane.showInputDialog
("Enter your number (Format: XXX-L)");
hireDate = JOptionPane.showInputDialog("Enter your hire date");
shift = Integer.parseInt(JOptionPane.showInputDialog
("Please enter the work shift for the employee:\n"
+ "\tEnter 1 for the day shift"
+ "\n\tEnter 2 for the night shift"));
payRate = Double.parseDouble(JOptionPane.showInputDialog
("Enter your pay rate"));
monthlyBonus = Double.parseDouble(JOptionPane.showInputDialog
("Enter your monthly bonus"));
RTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your required traing hours"));
CTH = Double.parseDouble(JOptionPane.showInputDialog
("Enter your training hours attended"));
//Production worker object
TeamLeader driver = new TeamLeader(name, number,
hireDate, shift, payRate, monthlyBonus, RTH, CTH);
JOptionPane.showMessageDialog(null,
"----------- Employe Info ----------------"
+ "\nName: " + driver.getName()
+ "\nEmployee Number: " + driver.getNumber()
+ "\nHire Date: " + driver.getHireDate()
+ "\nPay Rate: " + driver.getPayRate()
+ "\nShift: " + driver.getShift()
+ "\nMonthly Bonus: " + driver.getmonthlyBonus()
+ "\nRequired Training Hours: " + driver.getRTH()
+ "\nTraining Hours Attended: " + driver.getCTH());
System.exit(0);
}
}
You never call the setters of CTH and RTH. You pass their values to your constructor but don't use them.
Add to your constructor setting of CTH and RTH :
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You're calling the parent (super) constructor, but it doesn't take RTH or CTH, and you never set RTH and CTH on your TeamLeader object.
public TeamLeader(String name, String number, String hd, int shift,
double rate, double monthlyBonus, double RTH, double CTH)
{
super(name, number, hd, shift, rate);
this.monthlyBonus = monthlyBonus;
this.RTH = RTH;
this.CTH = CTH;
}
You are not setting the passed RTH to the instance's RTH. See code above for the fix
Related
I am getting an error that says: C:\Users\Jasmi\payroll\src\Payroll.java:68:38
java: variable grossPay might not have been initialized, but I am not sure how to fix it.
public class Payroll {
public String calculateGrossPay;
public String calculateNetPay;
private String name;
private int idNumber;
private double hourlyPayRate;
private double hoursworked;
Payroll(String nameGiven, int idNumbergiven) {
name = nameGiven;
idNumber = idNumbergiven;
hourlyPayRate = 7.15;
hoursworked = 0;
}
public String getName() {
return name;
}
public int getIDNumber() {
return idNumber;
}
public double getHourlyPayrate() {
return hourlyPayRate;
}
public double getHoursWorked() {
return hoursworked;
}
public void setName(String nameGiven) {
name = nameGiven;
}
public void setIDNumber(int idNumbergiven) {
idNumber = idNumbergiven;
}
public void setHourlyPayRate(double hourlypayrategiven) {
hourlyPayRate = hourlypayrategiven;
}
public void setHoursWorked(double hoursworkedgiven) {
hoursworked = hoursworkedgiven;
}
//gross pay plus overtime
public double calculateGrossPay() {
double overtime;
overtime = 0;
double grossPay;
if (hoursworked < 40) grossPay = hourlyPayRate * hoursworked;
else {
overtime = hoursworked - 40;
grossPay = (overtime * 1.5 * hourlyPayRate) + (40 * hourlyPayRate);
}
return grossPay;
}
//deductions
public double calculateNetPay() {
double netPay;
double grossPay;
double deduction = (.2579) * grossPay;
return netPay;
}
}
Here is the second document:
import javax.swing.JOptionPane;
public class PayrollClassTest {
public static void main(String[] args) {
String userInputString;
String userName;
int userId;
double userhourlyPayRate;
double userHoursworked;
userName = JOptionPane.showInputDialog("enter the name of this employee: ");
userInputString = JOptionPane.showInputDialog("Please enter employee ID: ");
userId = Integer.parseInt(userInputString);
userInputString = JOptionPane.showInputDialog("Please enter Hourly Pay Rate: ");
userhourlyPayRate = Double.parseDouble(userInputString);
userInputString = JOptionPane.showInputDialog("Enter the hours worked: ");
userHoursworked = Double.parseDouble(userInputString);
Payroll payroll1 = new Payroll(userName, userId);
payroll1.setHourlyPayRate(userhourlyPayRate);
payroll1.setHoursWorked(userHoursworked);
System.out.println(payroll1.getName() + " has a gross pay of " + payroll1.calculateGrossPay());
System.out.println(payroll1.getName() + " has a net pay of " + payroll1.calculateNetPay());
System.exit(0);
}
private static void calculateGrossPay() {
}
private static void calculateNetPay() {
}
}
I have tried to change deductions to be shown as this:
//deductions
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
}
It does work, but the results do not show the deductions:
Here is an example of the results:
Betty has a gross pay of 13000.0
Betty has a net pay of 0.0
Process finished with exit code 0
This is when I put name as Betty, gross pay as 100, and hours worked as 100. It shows the overtime correctly, but not the deductions.
Any help is greatly appreciated. thanks!
If my understanding of the code is correct then the following is where you are wrong for this piece of code.
public double calculateNetPay() {
double netPay = 0;
double grossPay = 0;
double deduction = (.2579) * grossPay;
return netPay;
}
First: netPay has no value assigned
This method will always return 0.
Reason : The netPay variable is declared and initialized to 0.
What you probably want to do before your return statement is perhaps;
netPay = grossPay - deduction;
I could be wrong in that logic, but I am definitely right when I say that you need to put some value to netPay before you return it.
Second: grossPay has no value assigned
In this method, you multiple .2579 with grossPay, but grossPay is 0 that you have now initialized.
You are assuming that the variable grossPay is shared for the two methods calculateGrossPay and calculateNetPay.
That is not true.
These are both two separate local variables that are declared separately in two different methods and have two different scopes.
You can read more about scope of java variables here:
variable docs from oracle
"in scope" meaning in java : StackOverflow question
My recommendation is to make grossPay a class variable instead of a method variable so that it could be shared between the two methods of the same class instance. (Assuming you are calling calculateGrossPay before calculateNetPay every time, so that grossPay can have the right value assigned to it.)
Attached is my finalized code for a Lab project. I have everything done but for some reason my code sits idle? I think it may be an issue between the "bank1" and "bank2" objects and the Bank class?
I apologize that the code is so long, as I don not know where the issue is. Help please :(
Currency Exchange Class (main)
import javax.swing.*;
import java.io.FileNotFoundException;
import java.util.*;
public class CurrencyExchange {
public static void main(String [] args) throws FileNotFoundException {
//Create 2 bank objects, one for each file "bank1.txt" & "bank2.txt"
Bank bank1 = new Bank("bank1.txt");
Bank bank2 = new Bank("bank2.txt");
int userCont = 0;
do {
boolean buy = false;
double amount;
int banksSupported = 0;
String currencyCode;
Scanner keyboard = new Scanner(System.in);
String userAnswer;
//Ask user to buy or sell - use continue to repeat loop if invalid
System.out.println("Do you want to buy or sell?");
userAnswer = keyboard.nextLine();
if (!userAnswer.equalsIgnoreCase("buy") && (!userAnswer.equalsIgnoreCase("sell")) ) {
System.out.println("Invalid response. Please enter buy or sell. ");
continue;
}
if (userAnswer.equalsIgnoreCase("buy")) {
buy = true;
}
//Ask user for foreign currency - use continue to repeat loop if invalid
System.out.println("Which currency would you like to use?");
currencyCode = keyboard.nextLine().toUpperCase();
//Check and Print how many banks support the users currency - use continue to repeat loop if none
if(bank1.supportCurrency(currencyCode))
++banksSupported;
if(bank2.supportCurrency(currencyCode))
++banksSupported;
if (banksSupported == 0) {
System.out.println("There are no banks the support " + currencyCode + ". Please enter a different currency.");
continue;
}
else if (banksSupported == 1) {
System.out.println("One bank supports " + currencyCode + ".");
}
else {
System.out.println("Two banks support " + currencyCode + ".");
}
//Prompt the user for the amount of foreign currency and get the user input
System.out.println(" What amount of " + currencyCode + "?");
amount = keyboard.nextDouble();
//Use the quoteBuy or quoteSell methods of the Bank objects to get a Quote from every bank supporting the foreign currency.
//Print the quote(s) from the bank(s), using the toString method of the Quote object(s).
if(buy) {
if (bank1.supportCurrency(currencyCode)) {
System.out.println(bank1.quoteBuy(amount, currencyCode));
}
if (bank2.supportCurrency(currencyCode)) {
System.out.println(bank2.quoteBuy(amount, currencyCode));
}
}
else {
if (bank1.supportCurrency(currencyCode)) {
System.out.println(bank1.quoteBuy(amount, currencyCode));
}
if (bank2.supportCurrency(currencyCode)) {
System.out.println(bank2.quoteBuy(amount, currencyCode));
}
}
//Use the console to prompt the user for another transaction.
userCont = JOptionPane.showConfirmDialog(null, "Would you like to preform another transaction?", "Contniue", JOptionPane.YES_NO_OPTION);
} while(userCont == 0); // while ( the user wants to continue performing transactions )
}
}
Bank Class
import java.io.*;
import java.util.*;
public class Bank {
// Five private data fields: The name of the bank, The commission rate, Three fields for the three currencies exchanged by the bank.
// Each of these should have type Currency.
private String bankName;
private double commissionRate;
private Currency currencyCode1;
private Currency currencyCode2;
private Currency currencyCode3;
public Bank(String fileA) throws FileNotFoundException {
File bankFile = new File(fileA);
Scanner keyboard = new Scanner(System.in);
this.bankName = keyboard.nextLine();
this.commissionRate = Double.parseDouble((keyboard.nextLine()));
this.currencyCode1 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
this.currencyCode2 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
this.currencyCode3 = new Currency(keyboard.next(), Double.parseDouble(keyboard.next()));
keyboard.close();
}
public boolean supportCurrency(String currencyCode) {
return currencyCode.equalsIgnoreCase(currencyCode1.getCurrencyCode())
|| currencyCode.equalsIgnoreCase(currencyCode2.getCurrencyCode())
|| currencyCode.equalsIgnoreCase(currencyCode3.getCurrencyCode());
}
// Working on getRate method.
public double getRate(String currencyCode) {
double bankExchangeRate = -1.0;
if (currencyCode.equalsIgnoreCase(currencyCode1.getCurrencyCode())) {
bankExchangeRate = currencyCode1.getExchangeRate();
}
else if (currencyCode.equalsIgnoreCase(currencyCode2.getCurrencyCode())) {
bankExchangeRate = currencyCode2.getExchangeRate();
}
else if (currencyCode.equalsIgnoreCase(currencyCode3.getCurrencyCode())) {
bankExchangeRate = currencyCode3.getExchangeRate();
}
return bankExchangeRate; //return -1.0
}
public Quote quoteBuy(double amt, String currencyCode) {
double rate = getRate(currencyCode);
Quote quote;
if(rate == -1.0) {
quote = null;
}
else {
double userOwes = amt / (rate * (1 - commissionRate)); // This calculates the commission amount based on the dollar amount.
double commission = userOwes * commissionRate;
quote = new Quote(bankName, "USD", userOwes, currencyCode, amt, commissionRate, commission);
}
return quote;
}
public Quote quoteSell(double amt, String currencyCode) {
double rate = getRate(currencyCode);
Quote quote;
if(rate == -1.0) {
quote = null;
}
else {
double base = amt / rate; // This calculates the dollar value of the foreign currency.
double commission = commissionRate * base; // This calculates the commission amount based on the dollar amount.
double amtConverted = base - commission; // The bank takes a cut.
quote = new Quote(bankName, currencyCode, amt, "USD", amtConverted, commissionRate, commission);
}
return quote;
}
}
Currency Class
public class Currency {
// Two private data fields, one to hold the currency code and one to hold the exchange rate.
// Note that the exchange rate for the same currency could be different for different banks
private final String currencyCode;
private final double exchangeRate;
// A constructor that takes two arguments: the currency code and exchange rate.
// The constructor should assign the private members from the values of the arguments.
public Currency(String currencyCode, double currencyExchangeRate) {
this.currencyCode = currencyCode;
this.exchangeRate = currencyExchangeRate;
}
// An accessor method (getter) for each data field.
public String getCurrencyCode() {
return currencyCode;
}
public double getExchangeRate() {
return exchangeRate;
}
}
Quote Class
import java.text.DecimalFormat;
public class Quote {
private String bankName;
private String codeToBank;
private double amtToBank;
private String codeFromBank;
private double amtFromBank;
private double commissionRate;
private double commissionAmt$;
DecimalFormat decimalFormat;
public Quote(String bankName, String currencyCode, double amt, String usd, double amtConverted, double commissionRate, double commission) {
this.bankName = bankName;
this.codeToBank = currencyCode;
this.amtToBank = amt;
this.codeFromBank = usd;
this.amtFromBank = amtConverted;
this.commissionRate = commissionRate;
this.commissionRate = commission;
this.decimalFormat = new DecimalFormat("0.00");
}
public String toString() {
return (this.bankName + " is willing to offer you " + decimalFormat.format(this.amtFromBank)
+ " " + this.codeFromBank + " for "
+ decimalFormat.format(this.amtToBank) + " "
+ this.codeToBank + ", after collecting a commission of "
+ decimalFormat.format(this.commissionRate)
+ " USD (" + Math.round(100 * this.commissionRate) + "%)");
}
}
Your issue is that your Scanner is reading from System.in, when it should be reading from the input files "bank1.txt" or "bank2.txt".
Change this line in Bank:
Scanner keyboard = new Scanner(System.in);
to this:
Scanner keyboard = new Scanner(bankFile);
And your code will work as intended.
new to Java and trying to set up get and set methods. Although one I need to do as calculation based off getSalary() multiplied by getMonths() to get a Year to Date total.
I haven't been able to find out if calculations are possible in get or set methods or I may just be such a newbie I have it in the wrong place.
public class Employee_v2
{
//Instance variables
private String first_name;
private String last_name;
private double salary;
private int months;
final double increase= 0.25;
private double year_to_date;
public Employee_v2()
{
//fill in the code to set default values to the instance variables
first_name="";
last_name="";
salary= 0.0;
months= 0;
}
//Constructor initializing instance variables with arguments
public Employee_v2(String f, String l, Double sal, int mo)
{
first_name = f;
last_name = l;
salary = sal;
months = mo;
}
//set arguments
public void setFirst(String f)
{
first_name = f;
}
public void setLast (String l)
{
last_name = l;
}
public void setSalary (double sal)
{
salary = sal;
}
public void setMonths (int mo)
{
months = mo;
}
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
//get arguments
public String getFirst()
{
return first_name;
}
public String getLast()
{
return last_name;
}
public double getSalary()
{
return salary;
}
public int getMonths()
{
return months;
}
public double getYtdSalary()
{
return yearToDateSal;
}
//DISPLAY
public void displayEmployee()
{
//display the name and salary of both Employee objects
System.out.println("Employee first name: " + getFirst());
System.out.println("Employee last name: " + getLast());
System.out.printf("Employee salary: $%.2f\n", getSalary());
//complete the code
System.out.println("-------------------------------");
//Determine the year to date salary for both employee
System.out.printf(getFirst() + "'s salary: $%.2f\n", getSalary());
// System.out.println(jas.getSalary());
System.out.printf("Year to date salary: $%.2f\n", getYtdSalary());
//set and display salary with increase
setSalary(getSalary()+ getSalary()*increase);
System.out.printf("New Salary: $%.2f\n", getSalary());
System.out.println();
System.out.println();
}//end method
}//end Class
Calculation are possible in getter and setter. I would do something like this:
public double getYtdSalary(){
double ytd = 0;
ytd = months * salary;
return ytd;
}
Like this you can calculate the year to date on the fly and is always accurate data. For example if you called the setMonths method you would also have to call the setYtdSalary before calling the getYtdSalary.
Also there is no need to call your getters in your class to access your private variables.
I would also suggest using Javadoc comment in your classes as they make it easier to understand what the methods do.
to answer your question: yes it is possible to do calculations
this is also needed in many places, as the main reason to use get and set methods is so you can check or manipulate the values before setting them in your class
I guess your Code will Crash on the printing of the year to date Salary, because the variable yearToDateSal is only valid in the Scope of your set Method.
public void setYtdSalary ()
{
double yearToDateSal;
yearToDateSal = getSalary() * getMonths();
}
you should declare your YearToDateSal variable in the beginning of the class, i.e. rigth after
final double increase= 0.25;
private double year_to_date;
private double yearToDateSal;
and in your setYtdSalary() remove the declaration of yearToDateSal;
this way you should be fine :)
This is what I have to do "Write a java application that prompts for the person ’ s information , instantiates an object of class Health Profile for that person and prints the information from that object — including the person ’ s First name , last name , gender , date of birth , height and weight — then calculates and prints the person ’ s age in years , BMI , maximum heart rate and target - heart - rate range . It should also
display the “ BMI values ” chart from Exercise 2 . 33 ." But I am getting errors whenever I run it.
Here is the code:
import java.util.*;
public class HealthProfile {
String firstName;
String lastName;
char gender;
int BirthMonth;
int BirthDay;
int BirthYear;
int height;
int weight;
public HealthProfile(String fName, String lName, char Genderr, int birthMonth, int birthDay, int birthYear, int heightt, int weightt){
firstName = fName;
lastName = lName;
gender = Genderr;
BirthMonth = birthMonth;
BirthDay = birthDay;
BirthYear = birthYear;
height = heightt;
weight = weightt;
}
HealthProfile() {
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
public void setGender(char gender) {
this.gender = gender;
}
public char getGender() {
return gender;
}
public void setBirthMonth(int BirthMonth) {
this.BirthMonth = BirthMonth;
}
public int getBirthMonth() {
return BirthMonth;
}
public void setBirthDay(int BirthDay) {
this.BirthDay = BirthDay;
}
public int getBirthDay() {
return BirthDay;
}
public void setBirthYear(int BirthYear) {
this.BirthYear = BirthYear;
}
public int getBirthYear() {
return BirthYear;
}
public void setHeight(int height) {
this.height = height;
}
public double getHeight() {
return height;
}
public void setWeight(int weight) {
this.weight = weight;
}
public double getWeight() {
return weight;
}
public int Age(){
Calendar now = Calendar.getInstance();
int nowYear = now.get(Calendar.YEAR);
int nowMonth = now.get(Calendar.MONTH);
int nowDay = now.get(Calendar.DATE);
int day = now.get(Calendar.DATE);
int month = now.get(Calendar.MONTH);
int year = now.get(Calendar.YEAR);
if (nowMonth > BirthMonth);
return (nowYear - BirthYear);
}
public double getBMI(){
return (weight * 703)/(height * height);
}
public int MaxHeartRate(){
return 220-Age();
}
public double TargetHeartRate(){
return MaxHeartRate() * 0.85 + MaxHeartRate() * 0.5;
}
}
Here is the test part:
import java.util.Scanner;
public class HealthProfileTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String firstName;
String lastName;
String DoB;
String theMonth;
String theDay;
String theYear;
char gender;
int Month;
int Day;
int Year;
double height = 0.0;
double weight;
HealthProfile personalInfo = new HealthProfile();
System.out.println("Enter your first name: ");
firstName = input.nextLine();
System.out.println("Enter your last name: ");
lastName = input.nextLine();
System.out.println("Male or female: ");
gender = input.nextLine().charAt(0);
System.out.println("Enter your date of birth in mm/dd/yyyy format: ");
DoB = input.nextLine();
theMonth = DoB.substring(0,2);
theDay = DoB.substring(3,5);
theYear = DoB.substring(6,10);
Month = Integer.parseInt(theMonth);
Day = Integer.parseInt(theDay);
Year = Integer.parseInt(theYear);
System.out.println("Enter your height in inches: ");
height = input.nextInt();
System.out.println("Enter your weight in pounds: ");
weight = input.nextInt();
System.out.println("Name: " + personalInfo.getFirstName() + personalInfo.getLastName());
System.out.println("Gender: " + personalInfo.getGender());
System.out.println("DoB: " + personalInfo.getBirthMonth() + "/" + personalInfo.getBirthDay() + "/" + personalInfo.getBirthYear());
System.out.println("Height: " + personalInfo.getHeight());
System.out.println("Weight: " + personalInfo.getWeight());
System.out.println("Age: " + personalInfo.Age());
System.out.println("BMI: " + personalInfo.getBMI());
System.out.printf("Max heart rate: ", personalInfo.MaxHeartRate());
System.out.printf("Target heart rate: ", personalInfo.TargetHeartRate());
System.out.println(" ");
System.out.println( "BMI VALUES" );
System.out.println("Underweight: Under 18.5");
System.out.println("Normal: 18.5-24.9 ");
System.out.println("Overweight: 25-29.9");
System.out.println("Obese: 30 or over");
}
}
Here is the output:
Name: nullnull
Gender:
DoB: 0/0/0
Height: 0.0
Weight: 0.0
Age: 2013
Exception in thread "main" java.lang.ArithmeticException: / by zero
at HealthProfile.getBMI(HealthProfile.java:108)
at HealthProfileTest.main(HealthProfileTest.java:43)
Java Result: 1
I know I did everything right but just don't get why it's acting up.
You forgot to call methods setHeight and setWeight. Therefore those values are still 0 by default given that they are numeric primitive types. Obviously the product of 2 zero values equals 0 and dividing then by 0 produces an ArithmeticException
Try calling the methods after accepting the inputs.
System.out.println("Enter your height in inches: ");
height = input.nextInt();
personalInfo.setHeight((int) height);
System.out.println("Enter your weight in pounds: ");
weight = input.nextInt();
personalInfo.setWeight((int) weight);
Similarly set the "Birth" fields
personalInfo.setBirthMonth(Month);
personalInfo.setBirthDay(Day);
personalInfo.setBirthYear(Year);
Aside: Java naming conventions show that variables start with a lowercase letter such as day, month and year. Read about them here
Your exception clearly says Exception in thread "main" java.lang.ArithmeticException: / by zero
As you can see in your own output, height is 0, so when you get the BMI you divide by 0, which is not a legal operation at:
public double getBMI(){
return (weight * 703)/(height * height);
}
Make sure you run your program fully and input a valid height.
Also, as #jlordo pointed out, your code is doing integer division (since all the values involved are integers. This will make you lose anything after the decimal point. Try using:
public double getBMI(){
return ((double)weight * 703)/(height * height);
}
Instead. Casting one of the involved values to a double makes Java keep the decimal values around.
In your following method, change it to something like this:
public double getBMI(){
if(height == 0)
return (weight * 703)/(height * height);
else
return x; // x is whatever the value you want
}
I am completed the whole program, and it is working fine. But, I am having trouble with the StringTokenizer. I have class named Worker.java and a test class named TestWorker.java...
In the test class I have calculated and printed out the total hoursworked, grossSalary and etc..
But I am stuck in 1 position, that is I have to store name,id, and hourly rate in array, and then using the StringTokenizer, I have to prompt the user to enter worker ID and hourly rate.
When the user enter the user worker name and ID, the program output will show the user the hourly rate of the worker...
or in other words...
Allow the user to enter worker-ID and Hours repeatedly until user enter and empty string. Read the values and invoke the methods addWeekly() on the appropriate object(by searching through the array to locate the object with the specified ID). If a nonexistent ID is entered display an appropriate error message.
Please see my codings below and modify as your needs....
//Worker.java
public class Worker {
public final double bonus=100;
protected String name;
protected String workerID;
protected double hourlyRate;
protected double hoursWorked;
protected double weekHour;
protected double tax;
protected double grossSalary;
protected double netSalary;
public Worker() {
}
public Worker(String name,String workerID,double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double weekHour){
hoursWorked = hoursWorked + weekHour;
}
public double gross()
{
grossSalary = (hoursWorked*hourlyRate);
if(hoursWorked>=150)
{
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double taxAndNet()
{
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary-tax);
return netSalary;
}
public String getName()
{
return name;
}
public String getWorkerID()
{
return workerID;
}
public double getHourly()
{
return hourlyRate;
}
public double getTotalHours()
{
return hoursWorked;
}
public double getGrossSalary()
{
return grossSalary;
}
public void addToGross(double amt)
{
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name :" + name + "\nID :" + workerID +"\nHourly rate : "+ hourlyRate +"\nTotal Hours Worked " + hoursWorked +"\nGross Pay: "+getGrossSalary()+ "\nTax : "+tax +"\nNetpay :" +netSalary);
}
}
//TestWorker.java
import java.util.StringTokenizer;
import java.util.Scanner;
public class TestWorker {
public static void main(String args[]) {
Worker e = new Worker("John Major","s123",15.0);
e.addWeekly(45);
e.addWeekly(40);
e.addWeekly(32);
e.addWeekly(38);
e.gross();
e.taxAndNet();
e.displaySalary();
Worker[] worklist = new Worker[5];
worklist[0] = new Worker("Richard Cooper","s1235",20.0);
worklist[1] = new Worker("John Major","s1236",18.0);
worklist[2] = new Worker("Mary Thatcher","s1237",15.0);
worklist[3] = new Worker("David Benjamin","s1238",16.0);
worklist[4] = new Worker("Jack Soo","s1239",25.0);
Scanner input = new Scanner(System.in);
String name;
do{
System.out.print("Please enter your name and worker ID: ");
name = input.nextLine();
StringTokenizer string = new StringTokenizer(name,"+");
System.out.println("******|||||*******");
while(string.hasMoreElements()){
System.out.println(string.nextElement());
}
}
while(name.isEmpty()==false);
String s = "Five+Three=Nine-One";
String arr[];
//declare it with 3 tokens as seen above:
StringTokenizer st = new StringTokenizer(s, "+=-");
//the array size is the number of tokens in the String:
arr = new String[st.countTokens()];
//when there are still more tokens, place it in the array:
int i = 0;
while(st.hasMoreTokens()){
arr[i] = st.nextToken();
i++;
}
//determine the word with the largest length:
int indexMax = 0;
for( i = 1; i < arr.length; i++){
if(arr[i].length() > arr[indexMax].length())
indexMax = i;
}
System.out.println("The largest element is in index: "
+ indexMax);
} //main
} //class
Please tell us your java version. Since jdk 1.4.2 you should use String.split(...) instead of the old Stringtokenizer. Check out this tutorial TIP: A little tutorial about String.split();