This program is supposed to run through a while loop twice. The first time it runs through, it displays the name, occupation, age, salary and salary w/bonus. Yet, when the loop runs through for a second time, the name field is blank and the salary w/bonus is added onto the salary of the first employee. Thanks.
import java.util.Scanner;
public class Worker {
public static void main(String[] args) {
String name;
int age;
String occupation;
double salary;
double total = 10000;
int count = 0;
Employee employeeInfo = new Employee();
Scanner keyboard = new Scanner(System.in);
while (count < 2) {
//User Name
System.out.println("Enter your name: ");
name = keyboard.nextLine();
employeeInfo.setEmployeeName(name);
keyboard.nextLine();
//User occupation
System.out.println("Enter your occupation: ");
occupation = keyboard.nextLine();
employeeInfo.setOccupation(occupation);
//User age
System.out.println("Enter your age: ");
age = keyboard.nextInt();
employeeInfo.setAge(age);
//User salary
System.out.println("Enter your salary: ");
salary = keyboard.nextDouble();
employeeInfo.setSalary(salary);
total = total + salary;
//Output information
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Occupation: " + occupation);
System.out.println("Original Salary: " + salary);
System.out.println("Salary with bonus: " + total);
count++;
}
// employeeInfo.greetingMessage("");
}
}
public class Employee {
private String employeeName;// Employee Name
private int age;// Employee Age
private String occupation;// Employee job title
private double salary;// Employee salary
// Setters
public void setEmployeeName(String name) {
employeeName = name;// Initializes employee name
}
public void setAge(int num) {
age = num;// Initializes employee age
}
public void setOccupation(String occu) {
occupation = occu;// Initializes occupation
}
public void setSalary(double num2) {
salary = num2;// Initializes salary
}
// Getters
public String getEmployeeName() {
return employeeName;
}
public int getAge() {
return age;
}
public String getOccupation() {
return occupation;
}
public double getSalary() {
return salary;
}
public void greetingMessage(String greeting){
System.out.println("Greetings " + getEmployeeName());
}
}
There is an issue with Scanner. You shouldn’t call
nextLineafternextInt– I read that here. You need to make a second scanner and use it to capture the numbers, like so:When you want a string use the first one and for a number use the second:
Also, instantiate your Employee object inside the while loop or it will be overwritten with each iteration.
Finally, remove the 2nd
nextLineafter you get the name but before you get the occupation.