How to list input values after the loop is done? - java

It is supposed calculate the sales commission based on input variables and list them after the loop is done.
I am unsure how to go about listing the values of totalEarned after because they change when the loop is done.
import java.util.Scanner;
public class SalesCommissionCalc
{
public static void main( String [] args )
{
final int SENTINEL = -1;
double grossSales;
double totalEarned;
Scanner scan = new Scanner( System.in );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
while ( grossSales != SENTINEL )
{
totalEarned =(500 + (grossSales * .08));
System.out.println( "Earned last week: $" + totalEarned );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
System.out.println( "Total Earned: $" + totalEarned );
}
}
}
Also if I added names to the program would I have to introduce another loop or would I be able to squeeze it into the same loop and keep the inputted names attached to the inputted values for when I list them after the loop?

You could save the values in a list and then retrieve and use them in the way you want to.
import java.util.Scanner;
public class SalesCommissionCalc
{
public static void main( String [] args )
{
final int SENTINEL = -1;
double grossSales;
double totalEarned;
//declare the list
List<double> earnings = new List<double>;
Scanner scan = new Scanner( System.in );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
while ( grossSales != SENTINEL )
{
totalEarned =(500 + (grossSales * .08));
//add the value to the list
earnings.add(totalEarned);
System.out.println( "Earned last week: $" + totalEarned );
System.out.print( "Enter gross sales for the last week, or -1 to stop > " );
grossSales = scan.nextDouble( );
System.out.println( "Total Earned: $" + totalEarned );
}
//retrieve the value at the third position in the list
earnings.get(3); //here you could also use a foreach or for loop to iterate through all list entries
}
}

You must retrieve the values by passing them in a list or an array.
List<double> earned = new List<double>;

Related

PiggyBank program with constructors, mutators, and accessors

There are two things I need assistance with. One is a problem with the rounding in the output and the other is just to find a better way to write my program that outputs the same results, if necessary.
What is the most efficient way to write this program? Even though it works like it should, I know it is not designed the best.
package program2;
import java.util.*;
class PiggyBank
{
Scanner console = new Scanner( System.in );
private int numPennies, numNickles, numDimes, numQuarters;
private float total;
public PiggyBank( int pennies, int nickles, int dimes, int quarters )
{
numPennies = pennies;
numNickles = nickles;
numDimes = dimes;
numQuarters = quarters;
total = (float) 0.00;
}
public void addPennies( int pennies )
{
System.out.println( "Have entered " + pennies + " pennies" );
if ( pennies < 0 )
{
System.out.println( "No Pennies Added" );
}
else
{
numPennies = numPennies + pennies;
total = (float) ( total + pennies * 0.01 );
}
}
public void addNickles( int nickles )
{
System.out.println( "Have entered " + nickles + " nickles" );
if ( nickles < 0 )
{
System.out.println( "No Nickles Added" );
}
else
{
numNickles = numNickles + nickles;
total = (float) ( total + nickles * 0.05 );
}
System.out.println( "Bank has $" + total + " in it" );
System.out.println();
}
public void addDimes( int dimes )
{
System.out.println( "Have entered " + dimes + " dimes" );
if ( dimes < 0 )
{
System.out.println( "No Dimes Added" );
}
else
{
numDimes = numDimes + dimes;
total = (float) ( total + dimes * 0.10 );
}
System.out.println( "Bank has $" + total + " in it" );
System.out.println();
}
public void addQuarters( int quarters )
{
System.out.println( "Have entered " + quarters + " quarters" );
if ( quarters < 0 )
{
System.out.println( "No Quarters Added" );
}
else
{
numQuarters = numQuarters + quarters;
total = (float) ( total + quarters * 0.25 );
}
}
public float getContents()
{
return total;
}
public final int breakTheBank()
{
if ( total >= 0 )
{
total = 0;
}
return (int) total;
}
}
public class PiggyBankTester
{
public static void main( String[] args )
{
Scanner console = new Scanner( System.in );
System.out.print( "Program By " );
String name = console.next();
System.out.println();
test();
}
public static void test()
{
PiggyBank bank = new PiggyBank( 0, 0, 0, 0 );
bank.addNickles( 3 );
bank.addPennies( 4 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
bank.addPennies( -18 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
bank.addDimes( 2 );
bank.addQuarters( 3 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
bank.addQuarters( -3 );
System.out.println( "Bank has $" + bank.getContents() + " in it \n" );
System.out.println( "Broke the bank and got $" + bank.getContents() + " from it \nBank has $" + bank.breakTheBank() + " in it" );
}
}
Here is a sample of my output. The float total rounded some of the results but I am not sure how to get it to round all of the results.
Program By JakeBrono46
Have entered 3 nickles
Bank has $0.15 in it
Have entered 4 pennies
Bank has $0.19000001 in it
Have entered -18 pennies
No Pennies Added
Bank has $0.19000001 in it
Have entered 2 dimes
Bank has $0.39000002 in it
Have entered 3 quarters
Bank has $1.14 in it
Have entered -3 quarters
No Quarters Added
Bank has $1.14 in it
Broke the bank and got $1.14 from it
Bank has $0 in it
I did use another site to find the structures for the accessors and mutators. I do not think I am missing anything too major, but I just can't think of what else I need to do at the moment.
find a better way to write my program that outputs the same results
import java.util.*;
import java.text;
class PiggyBank
{
Scanner console = new Scanner(System.in);
NumberFormat formatter = NumberFormat.getCurrencyInstance();
private int numPennies, numNickles, numDimes, numQuarters;
private float total;
public PiggyBank(int pennies, int nickles, int dimes, int quarters)
{
numPennies = pennies;
numNickles = nickles;
numDimes = dimes;
numQuarters = quarters;
total = 0.00;
}
I would use the NumberFormat class in the Text package. This way you can format numbers to your default currency (In this case dollars). You also do not need to cast float to your total variable since you declared it as a float instance variable.
bank.addPennies(4);
System.out.println("Bank has" + formatter.format(bank.getContents()) + " in it \n");
You use the formatter like so to print the formatted $#.## which allows you to avoid explicitly adding a dollar sign.
public final int breakTheBank()`
{
if(total >= 0)
{
total = 0;
}
return (int) total;
}
I would just change the if statement to if(total == 0) because you don't need to check if it's 0 if your going to change it to 0 anyway. Other than that there are not many changes that you can make.
One is a problem with the rounding in the output
Here is a method that I tend to use when rounding decimal numbers, so when you output a total just call it. More information can be found here about rounding numbers:
Round a double to 2 decimal places
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
find a better way to write my program that outputs the same results
If I was tasked to do this I would have used enumerations, where you can just create a enum value for every coin. If you're unsure on how to use enumerations take a look here for more information, https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
What you'd want to do in your case is to create a enum called Coins, where is takes a float of the value of that coin. Then create another method for instance addCoin where that would take a enum of coin and the amount to be added. Then simply calculate the result by accessing the value of the coin in the enum and multiplying it by the amount that's added.

How can I ask a user if they want to modify information and then apply the change?

This is a basic Java practice question that I have seen, but I wanted to step it up a notch and include functionalities that ask the user whether or not they want to modify an employee's information and if so which one, then apply the requested modifications to the employee and display the updated employees information one more time.
Here is my code thus far:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
private String decision;
// constructor to initialize first name, last name and monthly salary
public Employee( String first, String last, double salary )
{
firstName = first;
lastName = last;
if ( salary >= 0.0 ) // determine whether salary is positive
monthlySalary = salary;
} // end three-argument Employee constructor
// set Employee's first name
public void setFirstName( String first )
{
firstName = first;
} // end method setFirstName
// get Employee's first name
public String getFirstName()
{
return firstName;
} // end method getFirstName
// set Employee's last name
public void setLastName( String last )
{
lastName = last;
} // end method setLastName
// get Employee's last name
public String getLastName()
{
return lastName;
} // end method getLastName
// set Employee's monthly salary
public void setMonthlySalary( double salary )
{
if ( salary >= 0.0 ) // determine whether salary is positive
monthlySalary = salary;
} // end method setMonthlySalary
// get Employee's monthly salary
public double getMonthlySalary()
{
return monthlySalary;
} // end method getMonthlySalary
// set Employee's new monthly salary
public void setNewMonthlySalary( double salary )
{
monthlySalary = salary;
} // end method setMonthlySalary
// get Employee's new monthly salary
public double getNewMonthlySalary()
{
return monthlySalary;
} // end method getMonthlySalary
} // end class Employee
and the EmployeeTest class
import java.util.Scanner;
public class EmployeeTest
{
public static void main( String args[] )
{
Employee employee1 = new Employee( "Bo", "Jackson", 8875.00 );
Employee employee2 = new Employee( "Cam", "Newton", 13150.75 );
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
// display employees
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
// enter new employee salaries
System.out.println( "Enter " + employee1.getFirstName() + "'s new salary:" );
double newSalary1 = input.nextDouble();
employee1.setNewMonthlySalary( newSalary1 );
System.out.println( "Enter " + employee2.getFirstName() + "'s new salary:" );
double newSalary2 = input.nextDouble();
employee2.setNewMonthlySalary( newSalary2 );
// display employees with new yearly salary
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * newSalary1 );
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * newSalary2 );
} // end main
} // end class EmployeeTest
After displaying the employee information I would like to prompt the user to choose whether or not to make a change to an employee's salary. If so, then which employee. After the change is made I would like to display the the modified results. What would be the easiest way to handle this?
After some tweaking to my nested-ifs statements I figured out a way to achieve what I was looking for. I can't say that I was looking for answers to homework as I am no longer in school. I was simply looking for an easier way to achieve my goal by taking the path of least resistance...something that would have made coding easier and more concise. Although my answer is slightly bulkier than what I would have liked, it does still accomplish the task at hand. I will be working more to improve the application, but here is what I came up with:
import java.util.Scanner;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
public class EmployeeTest
{
public static void main( String args[] )
{
// create Scanner to obtain input from command window
Scanner input = new Scanner(System.in);
Employee employee1 = new Employee( "Bo", "Jackson", 8875.00 );
Employee employee2 = new Employee( "Cam", "Newton", 13150.75 );
// display employees
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
JDialog.setDefaultLookAndFeelDecorated(true);
int response1 = JOptionPane.showConfirmDialog(null, "Do you wnat to change an employee's salary?",
"Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response1 == JOptionPane.NO_OPTION)// if NO is clicked
{
System.out.println("See you next time");
} else if (response1 == JOptionPane.YES_OPTION)// if YES is clicked
{
// option to change the salary for employee 1
int response2 = JOptionPane.showConfirmDialog(null, "Would you like to change " + employee1.getFirstName() + " " + employee1.getLastName() + "'s salary:",
"Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response2 == JOptionPane.NO_OPTION)// if NO is clicked
{
// option to change the salary for employee 2
int response3 = JOptionPane.showConfirmDialog(null, "Would you like to change " + employee2.getFirstName() + " " + employee2.getLastName() + "'s salary:",
"Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response3 == JOptionPane.NO_OPTION)
{
System.out.println("See you next time");
} else if (response3 == JOptionPane.YES_OPTION)// if YES is clicked
{
// enter new salary for employee 2
System.out.println( "Enter " + employee2.getFirstName() + " " + employee2.getLastName() + "'s new salary:" );
double newSalary2 = input.nextDouble();
employee2.setNewMonthlySalary( newSalary2 );
// display unchanged salary for employee 1
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * employee1.getMonthlySalary() );
// display new yearly salary for employee 2
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * newSalary2 );
} else if (response3 == JOptionPane.CLOSED_OPTION)// if JOPTIONPANE is closed
{
System.out.println("JOptionPane closed");
}// END RESPONSE 3
} else if (response2 == JOptionPane.YES_OPTION)// if YES is clicked
{
// enter new salary for employee 1
System.out.println( "Enter " + employee1.getFirstName() + " " + employee1.getLastName() + "'s new salary:" );
double newSalary1 = input.nextDouble();
employee1.setNewMonthlySalary( newSalary1 );
// display new yearly salary for employee 1
System.out.printf( "Employee 1: %s %s; Yearly Salary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(),
12 * newSalary1 );
// display unchanged salary for employee 2
System.out.printf( "Employee 2: %s %s; Yearly Salary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(),
12 * employee2.getMonthlySalary() );
} else if (response2 == JOptionPane.CLOSED_OPTION)// if JOPTIONPANE is closed
{
System.out.println("JOptionPane closed");
}// END RESPONSE 2
{
}
} else if (response1 == JOptionPane.CLOSED_OPTION)// if JOPTIONPANE is clicked
{
System.out.println("JOptionPane closed");
}// END RESPONSE 1
} // end main
} // end class EmployeeTest
public class "Employee" did not change for post above.

time overflow mins secs and hours

im in need of some code to stop my current code
producing negative numbers if the start INTs are larger than the End INTs
Im aware there is a lot of code here i have commented out the bit i need help with (about half way down) but i wanted to provide it all so you ca complie and run to se what im struggling with
import javax.swing.JOptionPane;
public class race {
public static void main(String[] args) {
System.out.println("Course Start time End time Gender Total time Name");
int count = 1;
while (count<7){
count++;
System.out.println( "");
String colour = JOptionPane.showInputDialog(null,
"Competitor Enter your course colour first letter" );
String Starth = JOptionPane.showInputDialog(null,
"Competitor Enter your Start time (hours)" );
int Starthour=Integer.parseInt(Starth);
String Startm = JOptionPane.showInputDialog(null,
"Competitor Enter your Start time (mins)" );
int Startmin=Integer.parseInt(Startm);
String Starts = JOptionPane.showInputDialog(null,
"Competitor Enter your Start time (secs)" ) ;
int Startsec=Integer.parseInt(Starts);
String Endh = JOptionPane.showInputDialog(null,
"Competitor Enter your End time (hours)" );
int Endhour=Integer.parseInt(Endh);
String Endm = JOptionPane.showInputDialog(null,
"Competitor Enter your End Time (mins)" );
int Endmin=Integer.parseInt(Endm);
String Ends = JOptionPane.showInputDialog(null,
"Competitor Enter your End Time (secs)" );
int Endsec=Integer.parseInt(Ends);
String sex = JOptionPane.showInputDialog(null,
"Male or Female (M/F)" );
String Name = JOptionPane.showInputDialog(null,
"Competitor Enter your Full Name (Joe Bloggs)" );
int Timeh = (Endhour - Starthour);
int Timem = (Endmin - Startmin);
int Times = (Endsec - Startsec);
//so here i need code so that if i take endsec e.g50 away from startsec e.g54 Times wont print out -4, rather it will take one of Timem and print Times as 56//
System.out.print(colour);
System.out.print(" ");
System.out.print( String.format("%02d",Starthour));
System.out.print( ":");
System.out.print( String.format("%02d",Startmin));
System.out.print( ":");
System.out.print( String.format("%02d",Startsec));
System.out.print( " ");
System.out.print( String.format("%02d",Endhour));
System.out.print( ":");
System.out.print( String.format("%02d",Endmin));
System.out.print( ":");
System.out.print( String.format("%02d",Endsec));
System.out.print(" "+sex);
System.out.print(" "+Timeh);
System.out.print(":");
System.out.print(""+Timem);
System.out.print(":");
System.out.print(""+Times);
System.out.print(" "+Name);
}// end while
}
}

Arrays, Doubles, IF/Else

Im suppose to write a code using an Array of numbers and apparently not a string and they need to be double. The way I wrote the code, the only way I know how, works. Maybe im making it too complicated and an array would make it simple idk. Im new to programming, new as in a few days. please help.
What is needed is:
Write a code that will average the input of 10 numbers and show the avg along with if they pass or fail. if < 50 fail, else > 50 pass.
we have to use an array, we need to use JOptionPane.showMessageDialog., the numbers need to be double and rounded to two decimals.
I declared double but i get an error if i enter a decimal number. If i just run the code as is, it will let me enter 10 numbers, avg them and then tell me if i pass or fail. Im just lost when it comes to using the other factors. thanks
the working code follows:
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail {
public static void main(String[] args) {
String firstNumber,
secondNumber,
thirdNumber,
fourthNumber,
fifthNumber,
sixthNumber,
seventhNumber,
eighthNumber,
ninethNumber,
tenthNumber;
double number1,
number2,
number3,
number4,
number5,
number6,
number7,
number8,
number9,
number10,
sum;
firstNumber =
JOptionPane.showInputDialog ( "Enter 1st Grade" );
secondNumber =
JOptionPane.showInputDialog ( "Enter 2nd Grade" );
thirdNumber =
JOptionPane.showInputDialog ( "Enter 3rd Grade" );
fourthNumber =
JOptionPane.showInputDialog ( "Enter 4th Grade" );
fifthNumber =
JOptionPane.showInputDialog ( "Enter 5th Grade" );
sixthNumber =
JOptionPane.showInputDialog ( "Enter 6th Grade" );
seventhNumber =
JOptionPane.showInputDialog ( "Enter 7th Grade" );
eighthNumber =
JOptionPane.showInputDialog ( "Enter 8th Grade" );
ninethNumber =
JOptionPane.showInputDialog ( "Enter 9th Grade" );
tenthNumber =
JOptionPane.showInputDialog ( "Enter 10th Grade" );
number1 = Integer.parseInt ( firstNumber);
number2 = Integer.parseInt ( secondNumber);
number3 = Integer.parseInt ( thirdNumber);
number4 = Integer.parseInt ( fourthNumber);
number5 = Integer.parseInt ( fifthNumber);
number6 = Integer.parseInt ( sixthNumber);
number7 = Integer.parseInt ( seventhNumber);
number8 = Integer.parseInt ( eighthNumber);
number9 = Integer.parseInt ( ninethNumber);
number10 = Integer.parseInt ( tenthNumber);
sum = (number1 + number2 + number3 + number4 + number5 + number6 + number7 + number8 +number9 + number10)/10;
JOptionPane.showMessageDialog (
null, "The Average is " + sum, "Results",
JOptionPane.PLAIN_MESSAGE);
if (sum < 50){
JOptionPane.showMessageDialog (
null, "Fail", "Results",
JOptionPane.PLAIN_MESSAGE);
}else{
JOptionPane.showMessageDialog (
null, "Pass", "Results",
JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}
Woah there, that's a lot of repetition. You should probably clean this up with loops, like:
double sum = 0; // initialize variable for sum of all the numbers
for (int i = 1; i <= 10; i ++) { // go from 1 to 10
String strNum = JOptionPane.showInputDialog("Enter grade #" + i); // prompt for input
double dNum = Double.parseDouble(strNum); // convert to double
sum += dNum; // add to sum
}
double avg = sum / 10; // now get the average
number1 = Integer.parseInt ( firstNumber); expects to recieve a string that "looks like" an integer, if you give it something that "looks like" anything else you will recieve an error. You should instead use Double.parseDouble(firstNumber);
And yes, you should absolutely use an array for this. The use of arrays allows for a far shorter program;
public class UseArrays {
public static void main(String[] args){
int numberOfEntries=10
double[] numbers =new double[numberOfEntries];
for(int i=0;i< numbers .length;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
numbers[i]=Double.parseDouble(option);
}
double sum=0;
for(int i=0;i< numbers .length;i++){
sum+=numbers[i];
}
double average=sum/10;
System.out.println(average);
}
}
Note also that with the program created in this way it is incredibly easy to change the number of entries, in addition to being much shorter to write. You would not want to type out each entry by hand if you had hundreds, thousands or even millions of entries.
You could make this program even shorter by not storing each double then adding them later (which would also make using the array unnessissary). This program would look like;
public class DontUseArrays {
public static void main(String[] args){
int numberOfEntries=10
double sum=0;
for(int i=0;i< numberOfEntries;i++){
String option =
JOptionPane.showInputDialog ( "Enter Grade " + i );
double number=Double.parseDouble(option);
sum+=number;
}
double average=sum/10;
System.out.println(average);
}
}
Here's a fragment of code that should get you on your way:
public void test() {
double[] numbers = new double[10];
double sum = 0;
for ( int i = 0; i < numbers.length; i++ ) {
String number = JOptionPane.showInputDialog ( "Enter Grade "+(i+1) );
numbers[i] = Double.parseDouble(number);
sum += numbers[i];
}
}
What if you had to calculate 1000 grades? That's why we use arrays.
package avgpassorfail;
import javax.swing.JOptionPane;
public class Avgpassorfail
{
public static void main(String[] args)
{
String[] mumStr = new String[10];
double sum = 0;
for (int i = 0; i < numStr.length; i++) //0 to 10 (10 not included)
{
numStr[i] = JOptionPane.showInputDialog ( "Enter Grade " + (i+1)+ ": " );
sum += Double.parseDouble(numStr[i]);
}
double avg = sum / numStr.length;
JOptionPane.showMessageDialog (null, "The Average is " + avg, "Results", JOptionPane.PLAIN_MESSAGE);
if (avg < 50)
{
JOptionPane.showMessageDialog (null, "Fail", "Results", JOptionPane.PLAIN_MESSAGE);
}
else
{
JOptionPane.showMessageDialog (null, "Pass", "Results", JOptionPane.PLAIN_MESSAGE);
}
System.exit ( 0 );
}
}
To parse your Strings to the double type use Double.parseDouble(String s)
You can assign the ints returned from Integer.parseInt(String s) to your double variables, because doubles are higher precision than ints and so type conversion happens automatically without the need for an explicit cast.
However you can not parse any String with a decimal point to an int using Integer.parseInt(String s), by definition.
Additional point - There's no need to declare the String variables, or have a separate variable for each number - it'll be much cleaner to use an array and a loop to input the numbers, and possibly sum the numbers as they come in, something like:
double[] numbers = new double[10];
double sum = 0d;
for(int i = 0; i < numbers.length; i++ ) {
numbers[i] = Double.parseDouble(JOptionPane.showInputDialog ( "Enter 1st Grade" ));
sum += numbers[i];
}
double mean = sum / numbers.length;

Java: Calculating Employee's Wage

I have again a problem regarding on how to display the calculated wage of the employee..
When I type in the hourly rate, the Gross Salary won't display..
Here's what I've done so far..
The WageCalcu.java
public class WageCalcu
{
private String employeeName;
private int hours;
private double rate, pay;
public void setEmployeeName ( String name )
{
employeeName = name;
}
public String getEmployeeName()
{
return employeeName;
}
public double calculatePay( int hours, double rate )
{
if ( hours > 40 )
{
int extraHours = hours - 40;
pay = ( 40 * rate ) + ( extraHours * rate );
}
else pay = hours * rate;
return pay;
}
public void displayEmployee()
{
System.out.printf( "Employee's name: %s", getEmployeeName() );
System.out.printf( "\nGross Salary: ", + pay );
}
}
The Employee.java
import java.util.Scanner;
public class Employee
{
public static void main(String[] args)
{
Scanner input = new Scanner( System.in);
WageCalcu employee = new WageCalcu();
System.out.print( "Enter Employee %s name: " );
String name = input.nextLine();
employee.setEmployeeName( name );
System.out.print( "Enter how many hours worked: " );
int hours = input.nextInt();
System.out.print( "Enter hourly rate: " );
double rate = input.nextInt();
employee.calculatePay( hours, rate );
employee.displayEmployee();
System.out.println();
}
}
I'm sure you meant:
System.out.printf( "\nGross Salary: %f", pay);
One more thing
double rate = input.nextInt();
Should be
double rate = input.nextDouble();
If you're really expecting a real number.
I would put: System.out.printf( "\nGross Salary: %.2f", pay); to show 2 decimals.
You have missed %s in printf( "\nGross Salary: ", + pay );
Five years late to this party, but I'll speak my piece.
You've set it up to determine how many overtime hours an employee has, but you're not calculating their overtime pay.
What you have:
pay = ( 40 * rate ) + ( extraHours * rate );
What it should be:
pay = ( 40 * rate ) + ( extraHours * rate * 1.5);

Categories

Resources