Modify the AvgSalary code below to allow the user to set the counter value befor
ID: 3846516 • Letter: M
Question
Modify the AvgSalary code below to allow the user to set the counter value before entering into the loop.
//Imports
import java.util.Scanner;
//Begin Class SalAvg
public class SalAvg {
//Begin Main Method
public static void main(String[] args) {
//Declarations
int salCnt = 0;
double salary = 0;
double tot = 0;
double salAvg = 0;
//New Scanner object
Scanner sc = new Scanner(System.in);
//While loop to find average
while (salCnt < 5) {
System.out.printf("Enter the salary/hr amount %d: $", salCnt + 1);
salary = sc.nextDouble();
tot += salary; //Add entry to running total
salCnt += 1; //Increment the counter
}
//Determine the average
salAvg = tot / salCnt;
//Output the average
System.out.printf("The average of the %d salaries is: $%.2f ", salCnt, salAvg);
}
} //End Class SalAvg
Explanation / Answer
SalAvg.java
import java.util.Scanner;
//Begin Class SalAvg
public class SalAvg {
//Begin Main Method
public static void main(String[] args) {
//Declarations
int salCnt = 0;
double salary = 0;
double tot = 0;
double salAvg = 0;
//New Scanner object
Scanner sc = new Scanner(System.in);
System.out.print("Enter the counter value: ");
int counter = sc.nextInt();
//While loop to find average
while (salCnt < counter) {
System.out.printf("Enter the salary/hr amount %d: $", salCnt + 1);
salary = sc.nextDouble();
tot += salary; //Add entry to running total
salCnt += 1; //Increment the counter
}
//Determine the average
salAvg = tot / salCnt;
//Output the average
System.out.printf("The average of the %d salaries is: $%.2f ", salCnt, salAvg);
}
} //End Class SalAvg
Output:
Enter the counter value: 5
Enter the salary/hr amount 1: $1
Enter the salary/hr amount 2: $2
Enter the salary/hr amount 3: $3
Enter the salary/hr amount 4: $4
Enter the salary/hr amount 5: $5
The average of the 5 salaries is: $3.00
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.