Error code compiling: illegal start of expression [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Output Error :
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - illegal start of expression
I'm creating a class that calculate 1 student that take 3 quizzes 25%, 1 Midterm 25% , and 1 Final 50%
package Grading;
import java.util.Scanner;
public class Grading {
public static void main(String[] args) {
Scanner input =new Scanner(System.in);
public static double quiz1, quiz2, quiz3, midterm, finalExam, Grades, totalGrade, bothQuizzes, PfinalExam, PmidTerm;
public static String studentname;
public static int Score;
public String getstudentname( )
{
return studentname;
}
public double getquiz1()
{
return quiz1;
}
public double getquiz2 ()
{
return quiz2;
}
public double getquiz3 ()
{
return quiz3;
}
public double midterm()
{
return midterm;
}
public double finalExam()
{
return finalExam;
}
public void setquiz1 (double quiz1)
{
this.quiz1 = quiz1;
}
public void setquiz2 (double quiz2)
{
this.quiz2 = quiz2;
}
public void setquiz3 (double quiz3)
{
this.quiz3 = quiz3;
}
public void setmidterm()
{
this.midterm = midterm;
}
public void setfinalExam()
{
this.finalExam = finalExam;
}
public void setGrades ()
{
}
public String toString(){
return this.quiz1 + " " + this.quiz2 + this.quiz3 + " " + this.midterm + " " + this.finalExam;
}
public static void readInput(){
System.out.println("Please enter the grade you got for the first quiz: ");
quiz1 = grades.nextInt();
while (quiz1 <0 || quiz1>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz1 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the second quiz: ");
quiz2 = grades.nextInt();
while (quiz2 <0 || quiz2>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz2 = grades.nextInt();
}
System.out.println("Please enter the grade you got for the third quiz: ");
quiz3 = grades.nextInt();
while (quiz3 <0 || quiz3>10)
{
System.out.println("Please enter a grade between zero and ten: ");
quiz3 = grades.nextInt();
}
System.out.println("Please enter the grade you got on your midterm: ");
midterm = grades.nextInt();
while (midterm <0 || midterm>100)
{
System.out.println("Please enter a grade between 0 and 100: ");
midterm = grades.nextInt();
}
System.out.println("Please enter the grade you got on your final exam: ");
finalExam = grades.nextInt();
while (finalExam < 0 || finalExam > 100)
{
System.out.println("Please enter a grade between 0 and 100: ");
finalExam = grades.nextInt();
}
}
public static void output()
{
System.out.println(" your score for the first quiz was " + quiz1 );
System.out.println("your score for the second quiz was " + quiz2);
System.out.println("your score for the third quiz was " + quiz3);
System.out.println(" your score for the midterm was " + midterm );
System.out.println("your score for the final exam was " + finalExam);
bothQuizzes = ((quiz1 + quiz2 + quiz3)/100)*.25;
PmidTerm = (midterm/100) *.35;
PfinalExam = (finalExam/100) * .40;
System.out.println("Your total grade for these grades is " + totalGrade + "%");
System.out.println("Your total grade for these grades is " + totalGrade);
double letterGrade = totalGrade;
if (letterGrade >= 90)
{
System.out.println("Your grade is an A");
// grade = "A";
}
else if (letterGrade >= 80)
{
System.out.println("Your grade is a B");
}
else if (letterGrade >= 70)
{
System.out.println("Your grade is a C");
}
else if (letterGrade >= 60)
{
System.out.println("Your grade is a D");
}
else
{
System.out.println("Your grade is an F");
}
}}

I have re-written your program. I hope that this is what you wanted to achieve. I didn't know how you wanted to count the grade, so I've marked the place where you can change that code with a comment.
Since there were some major problems in your code with field declaration and function bodies, I've reorganized them. You can take a look at this code:
import java.util.Scanner;
public class Grading {
private int quiz1, quiz2, quiz3, midterm, finalExam; //quizzes exams tests what grades
public void readInput () {
Scanner in = new Scanner(System.in);
System.out.print("Please enter the grade you got for the first quiz: ");
quiz1 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the second quiz: ");
quiz2 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got for the third quiz: ");
quiz3 = readInt(in, 0, 10);
System.out.print("Please enter the grade you got on your midterm: ");
midterm = readInt(in, 0, 100);
System.out.print("Please enter the grade you got on your final exam: ");
finalExam = readInt(in, 0, 100);
}
public void output () {
System.out.println("Your score for the first quiz was " + quiz1);
System.out.println("Your score for the second quiz was " + quiz2);
System.out.println("Your score for the third quiz was " + quiz3);
System.out.println("Your score for the midterm was " + midterm);
System.out.println("Your score for the final exam was " + finalExam);
//dunno if this is the way you want to count it; change as needed
double quizzes = (quiz1 + quiz2 + quiz3) / 100 * 0.25;
double Pmidterm = midterm / 100 * 0.25;
double PfinalExam = finalExam /100 * 0.50;
double totalGrade = (quizzes + Pmidterm + PfinalExam) * 100.0;
char grade;
if (totalGrade >= 90)
grade = 'A';
else if (totalGrade >= 80)
grade = 'B';
else if (totalGrade >= 70)
grade = 'C';
else if (totalGrade >= 60)
grade = 'D';
else grade = 'F';
System.out.printf("Your grade is %c\n", grade);
}
private int readInt (Scanner in, int min, int max) {
int value = in.nextInt();
if (value < min || value > max) {
System.out.printf("Please enter a grade between %d and %d: ", min, max);
return readInt(in, min, max);
}
return value;
}
public static void main(String[] args) {
Grading grading = new Grading();
grading.readInput();
grading.output();
}
}

You never closed your main function

Related

Why do I only get one place behind my decimal point instead of two?

I have everything showing right when I try this problem except the decimal point place. I shows it should be xxx.xx and my answer only allows for xxx.x. Every time I try to fix it, I mess up everything else. Can you please help show me what I missed or did incorrectly? Here is what I have:
import java.util.Scanner;
import java.text.DecimalFormat;
public class TestAvgAndGrade{
static double average;
static char grade;
public static void main (String[] args){
Scanner keyboard = new Scanner(System.in);
char letter1;
char letter2;
char letter3;
char letter4;
char letter5;
double score1;
double score2;
double score3;
double score4;
double score5;
double score;
System.out.print("Enter test grade for student 1: ");
score1 = keyboard.nextDouble();
System.out.print("Enter test grade for student 2: ");
score2 = keyboard.nextDouble();
System.out.print("Enter test grade for student 3: ");
score3 = keyboard.nextDouble();
System.out.print("Enter test grade for student 4: ");
score4 = keyboard.nextDouble();
System.out.print("Enter test grade for student 5: ");
score5 = keyboard.nextDouble();
System.out.println("The letter grades are as follows:");
double average = calcAverage(score1, score2, score3, score4, score5);
System.out.println("Student 1: " + determineGrade(score1)
+ "\nStudent 2: " + determineGrade(score2)
+ "\nStudent 3: " + determineGrade(score3)
+ "\nStudent 4: " + determineGrade(score4)
+ "\nStudent 5: " + determineGrade(score5)
+ "\nThe average grade was: " + ((double)average));
}
public static double calcAverage(double score1, double score2, double score3, double score4, double score5) {
double average = (score1+score2+score3+score4+score5) / 5.0;
return average;
}
public static char determineGrade(double score){
if(score<=100 && score>=90)
{
return 'A';
}
else if(score>=80)
{
return 'B';
}
else if(score>=70)
{
return 'C';
}
else if(score>=60)
{
return 'D';
}
else
{
return 'F';
}
}
}
NumberFormat nf = NumberFormat.getNumberInstance(Locale.UK);
nf.setMinimumFractionDigits(2);nf.setMaximumFractionDigits(2);
System.out.println("The average grade was: " + nf.format(average));
//or Point or Comma alike
System.out.println("The average grade was: " + new DecimalFormat("##0.00").format(average));

java cumulative sum scanner method printf

I am new to java and having issues with my first project. I can't seem to get the variables in the correct scope and am unsure about the scanner methods. If anyone can help me with making it work it would be very helpful, thank you!
Create a new program called LetterGrade. Prompt the user to enter their name.
Create a method called calculateAvg(). Method should use a cumulative sum algorithm to prompt the user to enter 3 scores and calculate the average. Then, return that value to main.
Once the average is returned, Print the student's name and their average using printf() command. Create another method called printLetter(). Method should pass a parameter (average grade).
Use if … else if … else statements to print whether the student has an ‘A’, ‘B’, ‘C’, ‘D’, or ‘F’ average grade.
Grade Scale:
90-100 - A
80-89 - B
70-79 - C
60-69 - D
0-59 - F
Here is what I have so far:
import java.util.*;
public class LetterGrade {
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
Scanner console = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
return total;
}
public static double printLetter(int total) {
double total = console.nextDouble();
if (total < 60) {
System.out.print("You're grade is an F.");
} else if (total < 70) {
System.out.print("You're grade is a D.");
} else if (total < 80) {
System.out.print("You're grade is a C.");
} else if (total < 90) {
System.out.print("You're grade is a B.");
} else if (total <= 100) {
System.out.print("You're grade is an A.");
} else {
System.out.print("You have input an invalid number.");
}
}
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 0; i < 3; i++) {
System.out.print("Please enter score #" + (i+1) + ": ");
double next = console.nextDouble();
sum += next;
}
double total = (sum / 3);
return total;
}
public class LetterGrade{
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
printLetter(total);
}
public static double calculateAverage() {
double sum = 0.0;
double total = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
}
total = (sum / 3);
return total;
}
public static void printLetter(double total){
if (total < 60) {
System.out.print("You're grade is an F.");
}
else if (total < 70){
System.out.print("You're grade is a D.");
}
else if (total < 80){
System.out.print("You're grade is a C.");
}
else if (total < 90){
System.out.print("You're grade is a B.");
}
else if (total <= 100){
System.out.print("You're grade is an A.");
}
else{
System.out.print("You have input an invalid number.");
}
}
}
The immediate issue is that your for statement:
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + "? ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
does, not actually "loop" since you return during the very first iteration from it.
You probably want to move the last two lines where you calculate the total outside of it.
Other than that there were a few minor typos:
import java.util.Scanner;
class LetterGrade {
private static final int NUM_SCORES = 3;
public static void main(String[] args) {
System.out.printf("This program will calculate the average from %d scores and give you a letter grade.%n%n",
NUM_SCORES);
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
double average = calculateAverage(scanner);
System.out.printf("%nReport:%n");
System.out.printf("Name: %s%nAverage: %.2f%n", name, average);
printLetterGrade(average);
}
}
private static double calculateAverage(Scanner scanner) {
double total = 0;
for (int i = 1; i <= NUM_SCORES; i++) {
double next = getDoubleInput(scanner, String.format("Please enter score #%d: ", i), 0, 100);
total += next;
}
return total / NUM_SCORES;
}
private static void printLetterGrade(double average) {
if (average < 60) {
System.out.println("Your grade is a F.");
} else if (average < 70) {
System.out.println("Your grade is a D.");
} else if (average < 80) {
System.out.println("Your grade is a C.");
} else if (average < 90) {
System.out.println("Your grade is a B.");
} else {
System.out.println("Your grade is an A.");
}
}
private static double getDoubleInput(Scanner scanner, String prompt, double minValue, double maxValue) {
System.out.print(prompt);
double validDouble = -1;
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
validDouble = scanner.nextDouble();
if (validDouble >= minValue && validDouble <= maxValue) {
break;
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue,
maxValue);
System.out.print(prompt);
}
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validDouble;
}
}
Example Usage:
This program will calculate the average from 3 scores and give you a letter grade.
Enter your name: Megan
Please enter score #1: -100
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 105
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 99
Please enter score #2: 98
Please enter score #3: 100
Report:
Name: Megan
Average: 99.00
Your grade is an A.
Try it out here.
this problem is with your foor loop which with every iteration it reset its value. you can also write much simple code as below:
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
sum += console.nextDouble();
}
return (sum / 3);
}

Having issues running this code, I'm getting a .class error

I'm having issues getting this to run.
I can't manage to get the return value to work properly. I'm a few weeks into this course and I'm learning a lot but this project has been a little bit of a struggle for me.
I'm collecting data, creating an average and then using that average to output the corresponding letter grade.
Any help would be appreciated.
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
calculateAvg();
double avgScore;
printLetter(double);
}
public static void calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
for (double i = 0; i >0; i++)
{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
}
}
public static void printLetter(double avgScore)
{
Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
There are several errors in your program.
I have corrected the program with comments:
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore= calculateAvg();
printLetter(avgScore); //pass variable name here not datatype
}
public static double calculateAvg() //must have return type
{
Scanner console = new Scanner(System.in);
double avgScore;
// for (double i = 0; i 0; i++)
//{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
// avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
// }
}
public static void printLetter(double avgScore)
{
//Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
OUTPUT:
Enter your full name.
manisha
Enter test score 1
12
Enter test score 2
14
Enter test score 3
15
manisha, your average test score is: 13.7With that average, your grade is: F
You made many mistakes.
In the main method you should save the calculated average into the variable and pass it to the printLetter method like this
double avgScore = calculateAvg();
printLetter(avgScore);
The calculateAvg method return type should be double so you have to declare it like this
public static double calculateAvg()
Also the for loop inside calculateAvg is wrong and unnecessary so just remove it. And assigning the scanner.nextInt() value to the avgScore will discard the properly calculated value. so the calculateAvg method should be like this
The printLetter method is correct but contains unnecessary lines like
Scanner console = new Scanner(System.in); //Could be removed
The resulting code is
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore = calculateAvg();
printLetter(avgScore);
}
public static double calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
System.out.printf( "%s, your average test score is: %.1f\n", name, avgScore);
return avgScore;
}
public static void printLetter(double avgScore)
{
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
Checkout your main function. You have to assign the variable correctly to the return value of the calculateAvg method. Try this out:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
Also notice: double is the type of the variable, not the name. You have to give the name into the printLetter() method.
Another issue I just found is the doubled assigning of the avgScore variable which you have in your calculateAvg() method. Remove this line:
avgScore = console.nextInt();
This would force the user to again type in a value, which gets then assigned to the variable avgScore. This is not necessary.
Try to change the main method to this:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
There are some comments that I hope to be useful for you:
1- change the code in the main method to be like that
double avgScore = calculateAvg();
printLetter(avgScore);
2- check the use of the for loop (maybe you need a do while loop)
3- remove the scanner in "printLetter" method
4- also as #NiklasLehnfeld suggest to remove avgscore = console.nextInt();

Program is not quitting when choice 2 is entered instead it is asking to enter a positive number. What is the issue here?

The program is not quitting when choice 2 is entered instead it's asking to enter a positive value. It should only ask that if the choice was 1 and then the number of rooms entered was less than one. It should immediately quit the program but it's not. What can I do to fix this? Is it because of braces missing or extra ones.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Paint {
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
do {
displayMenu();
choice = keyboard.nextInt();
if (choice == 1) {
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
} while (choice != 2);
}
public static void displayMenu() {
System.out.println("1)Calculate Estimate");
System.out.println("2)Quit the program");
System.out.println("Please make a selection");
}
public static double numGallons(double sqr) {
return sqr / 115;
}
public static double numHours(double sqr) {
return (sqr / 115) * 8;
}
public static double laborCost(double cph, double nh) {
return cph * nh;
}
public static double paintCost(double ng, double cpg) {
return ng * cpg;
}
}
You should show the menu and get the choice before entering the loop, and at the end of the loop.
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat("###0.00");
Scanner keyboard = new Scanner(System.in);
double numbGallons;
double costPerGallon;
double totalSquareFeet = 0;
double numbHours;
double costPerHour;
double paintCost1;
double squareFeet;
int choice;
int numRooms = 0;
double laborCost1;
double totalEstimate;
displayMenu();
choice = keyboard.nextInt();
while (choice != 2) {
//if (choice ==1)
//{
System.out.println("How many rooms do you want to paint?");
numRooms = keyboard.nextInt();
//}
while (numRooms < 1) {
System.out.println("Please enter a positive value");
numRooms = keyboard.nextInt();
}
for (int counter = 1; counter <= numRooms; counter++) {
System.out.println("How many square feet of room " + counter +
" do you want to paint?");
squareFeet = keyboard.nextDouble();
totalSquareFeet = totalSquareFeet + squareFeet;
}
System.out.println("The total square feet is " + totalSquareFeet);
numbGallons = numGallons(totalSquareFeet);
numbHours = numHours(totalSquareFeet);
System.out.println("How much is the price per hour?");
costPerHour = keyboard.nextDouble();
System.out.println("How much is the price per gallon?");
costPerGallon = keyboard.nextDouble();
laborCost1 = laborCost(costPerHour, numbHours);
paintCost1 = paintCost(numbGallons, costPerGallon);
System.out.println("The number of Gallons is " + numbGallons);
System.out.println("The number of Hours is " + numbHours);
System.out.println("The labor cost is " + laborCost1);
System.out.println("The paint cost is " + paintCost1);
totalEstimate = laborCost1 + paintCost1;
System.out.println("The total estimate is " + totalEstimate);
displayMenu();
choice = keyboard.nextInt();
}
}

Finding out how many times a user is processed?

I'm having some trouble with a part of an assignment. I have to see how many times an employee is processed in my program, after the loop runs once it asks the user if they would like to process another. If they enter y for yes and then they enter n for end after the second employee calculation. I want it to say "Number of employees processed: 2". How could I do this?
package paytime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
String firstName, lastName, choice;
double hoursWorked, hourlyWage;
boolean processAnotherEmployee = true;
Employee one = new Employee();
while(true)
{
if (processAnotherEmployee)
{
System.out.print("Enter Y to process employee or any other key to end: ");
choice = scn.next();
if (choice.equalsIgnoreCase("Y"))
{
System.out.print("Enter employee number: ");
int number = scn.nextInt();
while (!one.findEmpNumber(number))
{
System.out.print("Invlaid, enter a proper employee number: ");
number = scn.nextInt();
}
System.out.print("Enter first name: ");
firstName = scn.next();
System.out.print("Enter last name: ");
lastName = scn.next();
System.out.print("Enter hours worked: ");
hoursWorked = scn.nextDouble();
while (hoursWorked < 0)
{
System.out.print("Negative hours not allowed. Enter hours worked: ");
hoursWorked = scn.nextDouble();
}
System.out.print("Enter hourly wage: $");
hourlyWage = scn.nextDouble();
while (hourlyWage < 0 || hourlyWage > 100)
{
System.out.print("Negative wage is not allowed or wage entered is to high. Enter hourley wage: $");
hourlyWage = scn.nextDouble();
}
double overtimeHours = hoursWorked - 40;
double overtimeWage = hourlyWage * 1.5;
System.out.println(" ");
if (hoursWorked <= 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
}
else if (hoursWorked > 40.0)
{
System.out.println("Worker " + number + " Paycheck Information: ");
System.out.println("Name is: " + firstName + " " + lastName);
System.out.println("Weekly Pay is: " + one.callWeeklyPay(hoursWorked, hourlyWage));
System.out.println("Income Taxes is: " + one.callIncomeTax());
System.out.println("Net Pay is: " + one.callNetPay());
System.out.println(" ");
System.out.println("Worker " + number + " Overtime Calculation: ");
System.out.println("Overtime Pay is: " + one.callOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked));
System.out.println("Overtime Income Tax is: " + one.callOvertimeTax());
System.out.println("Overtime Net Pay is: " + one.callOvertimeNetPay());
System.out.println("Total Net Pay is: " + one.callTotalNetPay());
System.out.println(" ");
}
}
else if (!choice.equalsIgnoreCase("Y"))
{
processAnotherEmployee = false;
System.out.println("Total number of Employees processed: ");
System.out.println(" ");
System.out.println("End of program");
break;
}
}
}
}
}
and
package paytime;
public class Employee {
private int empNumbers [] = {101, 103, 106, 109, 110, 113, 116, 118, 120};
public double weeklyPay, hoursWorked, hourlyWage, incomeTax, netPay,
overtimePay, overtimeHours, overtimeWage, overtimeIncomeTax,
overtimeNetPay, totalNetPay;
public boolean findEmpNumber(int number)
{
boolean found = false;
for (int sub = 0; sub < empNumbers.length; sub++)
{
if (number == empNumbers[sub])
{
found = true;
break;
}
}
return found;
}
private void calculateWeeklyPay(double hoursWorked, double hourlyWage) {
if (hoursWorked > 40)
{
hoursWorked = 40;
weeklyPay = hoursWorked * hourlyWage;
}
else
{
weeklyPay = hoursWorked * hourlyWage;
}
}
public double callWeeklyPay(double hoursWorked, double hourlyWage) {
calculateWeeklyPay(hoursWorked, hourlyWage);
return weeklyPay;
}
private void calculateIncomeTax() {
if (weeklyPay > 0.0 && weeklyPay <= 300.0)
{
incomeTax = weeklyPay * 0.10;
}
else if (weeklyPay > 300.1 && weeklyPay <= 400.0)
{
incomeTax = weeklyPay * 0.12;
}
else if (weeklyPay > 400.1 && weeklyPay <= 500.0)
{
incomeTax = weeklyPay * 0.15;
}
else if (weeklyPay > 500.1)
{
incomeTax = weeklyPay * 0.20;
}
}
public double callIncomeTax() {
calculateIncomeTax();
return incomeTax;
}
private void calculateNetPay() {
netPay = weeklyPay - incomeTax;
}
public double callNetPay() {
calculateNetPay();
return netPay;
}
private void calculateOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
overtimePay = overtimeHours * overtimeWage;
}
public double callOvertimePay(double overtimeHours, double overtimeWage, double hourlyWage, double hoursWorked) {
calculateOvertimePay(overtimeHours, overtimeWage, hourlyWage, hoursWorked);
return overtimePay;
}
private void calculateOvertimeTax() {
overtimeIncomeTax = overtimePay * 0.25;
}
public double callOvertimeTax() {
calculateOvertimeTax();
return overtimeIncomeTax;
}
private void calculateOvertimeNetPay() {
overtimeNetPay = overtimePay - overtimeIncomeTax;
}
public double callOvertimeNetPay() {
calculateOvertimeNetPay();
return overtimeNetPay;
}
private void calculateTotalNetPay() {
totalNetPay = netPay + overtimeNetPay;
}
public double callTotalNetPay() {
calculateTotalNetPay();
return totalNetPay;
}
}
You can achieve this by simply having "int employeesProcessed = 0;" outside of you while loop then add "employeesProcessed++;" directly after "if (choice.equalsIgnoreCase("Y"))" so that each time your program is asked to process an employ you add 1 to your int that is keeping track of how many employees you have processed. Then you can add this variable onto the end of your printed string so it says "Total number of Employees processed: " + employeesProcessed.

Categories