0% found this document useful (0 votes)
10 views6 pages

Java Programs for Math and Salary Calculations

Uploaded by

wwangyibo17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views6 pages

Java Programs for Math and Salary Calculations

Uploaded by

wwangyibo17
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Chapter 4

1. (Find the Two Largest Numbers) Using counter controlled while loop, write a program that find
the two largest values of the 10 values entered and print the result.

Program:
//[Link]
package CH_4;
public class TwoLargest{
private int fLargest = 0, sLargest = 0; // first and second largest

public void enterNumber(int x){


if(x > fLargest){
sLargest = fLargest;
fLargest = x;
}else if(x > sLargest){
sLargest = x;
}
}
public int getFirstLargest(){
return fLargest;
}
public int getSecondLargest(){
return sLargest;
}
}

//[Link]
package CH_4;
import [Link];

public class TwoLargestTest{


public static void main(String[] args){
Scanner input = new Scanner([Link]);
TwoLargest tl = new TwoLargest();

int counter = 1;
while(counter <= 10){
[Link]("%d/10. Enter number: ", counter);

int num = [Link]();


[Link](num);
counter++;
}

[Link]("First Largest: %d\nSecond Largest: %d\n",


[Link](), [Link]());
1
}
}

Output:
1/10. Enter number: 321
2/10. Enter number: 54
3/10. Enter number: 213
4/10. Enter number: 54
5/10. Enter number: 12
6/10. Enter number: 34
7/10. Enter number: 55
8/10. Enter number: 1
9/10. Enter number: 54
10/10. Enter number: 87
First Largest: 321
Second Largest: 213

2. (Factorial) Write an application that reads a nonnegative integer and computes and prints its
factorial. The factorial of a nonnegative integer n is written as n! (pronounced “n factorial”) and is
defined as follows:
n! = n · (n – 1) · (n – 2) · … · 1 (for values of n greater than or equal to 1) and
n! = 1 (for n = 0). For example, 5! = 5 · 4 · 3 · 2 · 1, which is 120.

Program:
// [Link]
package CH_4;
import [Link];

public class Factorial{


public static void main(String[] args){
Scanner input = new Scanner([Link]);

int num = 0;

while(num != -1) {
[Link]("Enter a number to compute its factorial (-1 to exit): ");
num = [Link]();
if(num != -1) {
int factorial = getFactorial(num);
[Link]("Factorial of %d is %d \n", num, factorial);
}
}
[Link]("Program's terminated!");
}
private static int getFactorial(int x){
int factorial = x;
while(x > 1){
2
x -= 1;
factorial *= x;
}
return factorial;
}
}

Output:
Enter a number to compute its factorial (-1 to exit): 5
Factorial of 5 is 120
Enter a number to compute its factorial (-1 to exit): 16
Factorial of 16 is 2004189184
Enter a number to compute its factorial (-1 to exit): -1
Program's terminated!

3. (Sales Commission Calculator) A large company pays its salespeople on a commission basis.
The salespeople receive $200 per week plus 9% of their gross sales for that week. For example, a
salesperson who sells $5000 worth of merchandise in a week receives $200 plus 9% of $5000, or a
total of $650. You’ve been supplied with a list of the items sold by each salesperson. The values of
these items are as follows:
Item Value
1 239.99
2 129.75
3 99.95
4 350.89
Develop a Java application that inputs one salesperson’s items sold for last week and calculates and
displays that salesperson’s earnings. There’s no limit to the number of items that can be sold.

Program:
// [Link]
package CH_4;
public class SalesCommissionCalculator{
private static final double BASE_PAY = 200.0;
private static final double COMMISSION_PERCENT = 0.09;
private double total;

public void enterItem(int x){


switch(x){
case 1:
total += 239.99;
break;
case 2:
total += 129.75;
break;
case 3:
total += 99.95;
3
break;
case 4:
total += 350.89;
break;
default:
[Link]("Invalid item number\n");
break;
}
}
public void displayEarning() {
[Link]("\nWEEKLY COMMISSION\n");
[Link]("Weekly sales total: %.2f\n", total);
[Link]("Weekly earnings: %.2f\n", calculateEarning());
}
public double calculateEarning(){
double salary = BASE_PAY + ( total * COMMISSION_PERCENT );
return salary;
}
}

// [Link]
package CH_4;
import [Link];

public class SalesCommissionCalculatorTest{


public static void main(String[] args){

Scanner input = new Scanner([Link]);


SalesCommissionCalculator saleComision = new SalesCommissionCalculator();

int item = 0;
while(item != -1){
[Link]("Enter the item number that just sold (-1 to exit): ");
item = [Link]();
if(item != -1) {
[Link](item);
}
}
[Link]();

}
}

Output:
Enter the item number that just sold (-1 to exit): 1
Enter the item number that just sold (-1 to exit): 2
Enter the item number that just sold (-1 to exit): 2
4
Enter the item number that just sold (-1 to exit): 5
Invalid item number
Enter the item number that just sold (-1 to exit): 4
Enter the item number that just sold (-1 to exit): -1

WEEKLY COMMISSION
Weekly sales total: 850.38
Weekly earnings: 276.53

4. (Salary Calculator) Develop a Java application that determines the gross pay for each of
three employees. The company pays straight time for the first 40 hours worked by each employee
and time and a half for all hours worked in excess of 40. Use the following list of the employees,
their
number of hours worked last week and their hourly rates. The program should input these
information for each employee, then determine and display the employee’s gross pay. Use class
Scanner to
input the data.
Employee Hours Rate
1 38 16.84
2 45 18.50
3 35 17.25
4 42 15.00

Program:
// [Link]
package CH_4;
public class SalaryCalculator{
private static double BASE_HOURS = 40.0;
private static double OVERTIME_RATE = 1.5;

private double hours, pay;

public void setHours(double h){


hours = h;
}
public void setHourlyPay(double hp){
pay = hp;
}
public double calculateGrossPay(){

double grossPay;
if(hours <= 40) {
grossPay = hours * pay;
}else {
double overTimeHours = hours - BASE_HOURS;
double overTimePay = overTimeHours * pay * OVERTIME_RATE;
double normalPay = (hours - overTimeHours) * pay;
5
grossPay = normalPay + overTimePay;
}
return grossPay;
}
}

// [Link]
package CH_4;
import [Link];

public class SalaryCalculatorTest{


public static void main(String[] args){
Scanner input = new Scanner([Link]);
SalaryCalculator salaryCalc = new SalaryCalculator();

int counter = 1;
while(counter <= 4){
[Link]("Employee %d weekly hours: ", counter);
double hour = [Link]();
[Link](hour);

[Link]("Employee %d hourly pay: ", counter);


double hourlyPay = [Link]();
[Link](hourlyPay);
[Link]("Employee %d gross pay: %.2f\n",counter,[Link]());
counter++;
}
}
}

Output:
Employee 1 weekly hours: 38
Employee 1 hourly pay: 16.84
Employee 1 gross pay: 639.92
Employee 2 weekly hours: 45
Employee 2 hourly pay: 18.5
Employee 2 gross pay: 878.75
Employee 3 weekly hours: 35
Employee 3 hourly pay: 17.25
Employee 3 gross pay: 603.75
Employee 4 weekly hours: 42
Employee 4 hourly pay: 15
Employee 4 gross pay: 645.00

Common questions

Powered by AI

The purpose of the OVERTIME_RATE constant in the SalaryCalculator program is to compute the additional pay due for hours worked beyond the regular 40-hour workweek. It represents the multiplier (1.5) applied to the base hourly rate to calculate overtime compensation. In the gross pay calculation, if an employee works more than 40 hours, the program determines overtime hours, calculates their pay at the overtime rate, and adds it to the regular pay, thereby accurately reflecting the increase in compensation for additional work hours .

The use of private variables in the TwoLargest and SalesCommissionCalculator classes encapsulates data by restricting direct access from outside the classes. For example, fLargest and sLargest in TwoLargest, and total in SalesCommissionCalculator are private, ensuring that only controlled, class-specific methods can alter their values. This encapsulation supports data integrity by preventing unintended modifications from external code, enforcing consistent data handling, and maintaining internal class invariants across operations .

Alternative strategies for enhancing user input validation in SalaryCalculator include implementing checks before processing to ensure the provided hours and pay rates fall within realistic ranges (e.g., hours cannot exceed a sensible workweek length, and pay cannot be negative). Real-time data validation could provide immediate feedback, preventing erroneous input acceptance. The program can also employ exception handling to address incorrect data types and use informative user messages to offer corrective guidance, improving overall user experience .

The SalesCommissionCalculator program handles invalid item inputs by using a switch statement to map item numbers to their corresponding values. If an entered item number does not match a defined case (1, 2, 3, or 4), it falls into the default branch, which outputs "Invalid item number" without terminating the program, allowing continued input of valid items. This design contributes to program robustness by ensuring that invalid entries do not affect the calculation process or crash the application .

The incremental approach to entering items sold in the SalesCommissionCalculator allows users to input sales data one item at a time, enhancing flexibility by supporting varied input sequences and accommodating sales tallies as they occur. This process allows for real-time update and ensures that users can correct mistakes or add additional items before finalizing entries. By not requiring all data upfront, the program is more user-friendly and aligns with realistic workflow scenarios in sales environments .

The TwoLargest program uses a counter-controlled while loop to process 10 user-entered integers. It maintains two variables, fLargest and sLargest, initialized to zero. For each number entered, the program checks if it is greater than fLargest. If so, it assigns the value of fLargest to sLargest and updates fLargest with the new number. If the number is not larger than fLargest but is greater than sLargest, it updates sLargest with this number. This approach ensures that the first and second largest numbers are tracked throughout the input process .

Using a while loop to control input in the TwoLargest program allows for a simple, easy-to-read structure that checks conditions before entry and operates a known number of times (10 entries). However, alternative approaches like for loops might provide clearer, more concise syntax suitable for fixed iterations. Unlike while loops, for loops inherently combine initialization, condition-checking, and updating in a single line, potentially reducing errors and improving maintainability by making iteration logic more visible upfront .

The factorial program can lead to incorrect results when handling large values due to integer overflow. Java integers are bounded by a maximum value, and computing the factorial of numbers like 16 leads to products that exceed this limit. As illustrated, computing 16! returns 2004189184, which is inaccurate due to overflow beyond the maximum representable integer value .

The iterative approach might be chosen in the factorial program over a recursive one to avoid the overhead of deep recursive calls and potential stack overflow errors associated with large input values. Iteration provides more robust handling of loop executions within the fixed stack space, ensuring consistent performance irrespective of input size. Additionally, iterative loops are often more intuitive and efficient for simple calculations and avoid additional memory allocations associated with the recursive call stack .

Improvements to handle larger numbers in the factorial calculation program include using a data type capable of representing larger values, such as BigInteger in Java, which can handle integers of arbitrary precision. Additionally, optimizing the algorithm by implementing memoization or iterative approaches to reduce redundant computation and using parallel processing can improve performance. These changes would enable accurate computation of factorials for significantly larger numbers than are feasible with standard integer types .

You might also like