We have to use set and get methods to such as
Employee()
Employee(empId:int)
Employee(empId:int, payRate:double, weeklyHrs:double)
setId(empId:int):void
setPayRate(payRate:double):void
setHrs(weeklyHrs:double):void
getId():int
getPayRate():double
getHrs():double
getWeeklyPay():double
toString():String
to create an employee class and employee class demo. We have to use two employee id's and type in their weekly hours and pay to return how much they made. Here is what I have down for the Employee class:
//#param
Scanner input = new Scanner(System.in); //Scanner object
public void setID(int empID){
System.out.println("Enter employee 1's id: ");
String input2 = input.next();
int emp1 = Integer.parseInt(input2);
System.out.println("Enter employee 2's id: ");
String input3 = input.next();
int emp2 = Integer.parseInt(input3);
}
//#param
public void setPayRate(double payRate){
System.out.println("Enter employee 1's payrate: ");
String input4 = input.next();
double pay1 = Double.parseDouble(input4);
System.out.println("Enter employee 2's payrate: ");
String input5 = input.next();
double pay2 = Double.parseDouble(input5);
}
//#param
public void setHrs(double weeklyHrs){
System.out.println("Enter employee 1's hours: ");
String input6 = input.next();
double hour1 = Double.parseDouble(input6);
System.out.println("Enter employee 2's hours: ");
String input7 = input.next();
double hour2 = Double.parseDouble(input7);
}
//GET METHODS
public int getID(int empID){
return empID;
}
public double getHrs(double hours){
return hours;
}
public double getWeeklyPay(double pay){
return pay;
}
//DISPLAY ANSWERS
public String toString(int emp1,int emp2,double hour1,double hour2,double pay1,double pay2){
String myString= String.format("The first employee's ID is: " + emp1 +
"The second employee's ID is: " + emp2 +
"The first employee's hours are: " + hour1 +
"The secondemployee's hours are: " + hour2 +
"The first employee's pay: $%,.2f"+ pay1*hour1 +
"The second employee's pay: $%,.2f" + pay2*hour2,
emp1,emp2,hour1,hour2,pay1,pay2);
return myString;
}
}//End of class
I'm just wondering what I would put in my Employee Class Demo so that it would be able to return the toString method?
System.out.println() calls the toString() method automatically on any object you pass into it - alternatively, you can just call it yourself:
Employee e;
// properly initialize e
System.out.println(e); // works
System.out.println(e.toString()); // also works
As a side note, your toString() method is incorrect. It should be a member function of the Employee class - making it a method that takes Employee objects is the wrong way to do it (assuming you want to follow standard Java OOP practices).
The proper method would look something like this:
// Notice no arguments are passed in
public String toString() {
// Instead, we use the "this" variable
return String.format("My ID is %s, my hours are %f, and my pay is $%,.2f", this.empID, this.hours, this.pay);
}
Related
I'm still a beginner so cut me some slack.
I have 5 class but only 2 are needed for my question. This is a question in my assignment so no need to be too particular. I have been tasked to make a java terminal system to store and display lecturer (part time and full time), lecturers address, and classes information.
My code will check if there is a part time lecturer to display (this includes the address object since it is part of the lecturer information) . If not, it will prompt the user to enter the part time lecturer details. When entering the part time details I am not sure on how to enter the address without recreating the object.
here is my codes
This is part time class
public class PartTime extends Lecturer{
private double hourlyRate;
private int hoursWorked;
//classR = class resposible
private ClassInfo classR;
PartTime(){
classR = new ClassInfo();
}
PartTime(String staffNo, String name, int contactNo, int noClasses, Address add, double hourlyRate, int hoursWorked, ClassInfo classR){
super(staffNo, name, contactNo, noClasses, add);
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
this.classR = classR;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public int getHoursWorked(){
return this.hoursWorked;
}
public void setHourlyRate(double newHourlyRate){
this.hourlyRate = newHourlyRate;
}
public void setHoursWorked(int newHoursWorked){
this.hoursWorked = newHoursWorked;
}
public void displayClassR(){
System.out.println("Class No : "+ classR.getClassNo());
System.out.println("Subject Name : "+ classR.getSubjectName());
System.out.println("Number Of Students : "+ classR.getNoStudents());
System.out.println("Start Date : "+ classR.getStartDate());
System.out.println("End Date : "+ classR.getEndDate());
}
}
This is lecturer class
public class Lecturer{
private String staffNo, name;
private int contactNo, noClasses;
private final Address add;
Lecturer(){
add = new Address();
}
Lecturer(String staffNo, String name, int contactNo, int noClasses, Address add){
this.staffNo = staffNo;
this.name = name;
this.contactNo = contactNo;
this.noClasses = noClasses;
this.add = add;
}
public String getStaffNo(){
return this.staffNo;
}
public String getName(){
return this.name;
}
public int getContactNo(){
return this.contactNo;
}
public int getNoClasses(){
return this.noClasses;
}
public void displayAdd(){
System.out.println("Unit Number : "+ add.getUnitNo());
System.out.println("Street Name : "+ add.getStreetName());
System.out.println("City : "+ add.getCity());
System.out.println("Postcode : "+ add.getPostcode());
}
public void setStaffNo(String newStaffNo){
this.staffNo = newStaffNo;
}
public void setName(String newName){
this.name = newName;
}
public void setContactNo(int newContactNo){
this.contactNo = newContactNo;
}
public void setNoClasses(int newNoClasses){
this.noClasses = newNoClasses;
}
public void setAdd(String newUnitNo, String newStreetName, String newCity, int newPostcode){
add.setUnitNo(newUnitNo);
add.setStreetName(newStreetName);
add.setCity(newCity);
add.setPostcode(newPostcode);
}
}
You can ignore the menu part
import java.io.*;
class Main{
static Scanner scan = new Scanner(System.in);
static Address add = new Address();
static ClassInfo classI = new ClassInfo();
static FullTime ft = new FullTime();
static PartTime pt = new PartTime();
static String staffNo, name, classNo, subjectName, startDate, endDate, unitNo, streetName, city;
static int contactNo, noClasses, hoursWorked, noStudents, postcode, select;
static double annualSalary, hourlyRate;
public static void main(String[] args){
//menu looping
do{
System.out.println("=======================");
System.out.println("| Main Menu |");
System.out.println("| Select an option |");
System.out.println("| 1. Lecturer |");
System.out.println("| 2. Class Info |");
System.out.println("| 3. File Actions |");
System.out.println("| 0. Exit |");
System.out.println("=======================");
select = scan.nextInt();
switch(select){
case 1:
lecturerMenu();
break;
case 2:
classInfoMenu();
break;
case 3:
fileMenu();
case 0:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Error please select again");
}
}while(select !=0);
}
Eventually it will make its way to the part where the user adds part time lecturer data. the set is incomplete as i didnt know how to do the addresspart
public static void newPartTime(){
System.out.println("Enter Part Time Lecturer Details");
System.out.print("Enter Staff Number: ");
scan.nextLine();
staffNo = scan.nextLine();
System.out.print("Enter Name: ");
name = scan.nextLine();
System.out.print("Enter Contact Number: ");
contactNo = scan.nextInt();
System.out.print("Enter Hourly Rate: ");
hourlyRate = scan.nextDouble();
System.out.print("Enter Hours Worked: ");
hoursWorked = scan.nextInt();
System.out.println("Enter Address");
System.out.print("Enter Unit Number: ");
scan.nextLine();
unitNo = scan.nextLine();
System.out.print("Enter Street Name: ");
streetName = scan.nextLine();
System.out.print("Enter City: ");
city = scan.nextLine();
System.out.print("Enter Postcode: ");
postcode = scan.nextInt();
scan.nextLine();
if(classI == null){
System.out.println("There is no class available. Please add a new class");
newClassInfo();
}else{
pt.setStaffNo(staffNo);
pt.setName(name);
pt.setContactNo(contactNo);
pt.setNoClasses(noClasses);
pt.set
}
}
}
Normally I would do this for my declaration:
static FullTime ft = new FullTime(var1, var1 ,var3, address);
Am I able to recreate the object or should I just add a method for set address in part time?
You could create an Object of the address class and set values to that and then set the object into your part time object.
I am working on a code where you have a students name and his grades and it prints his name total scores and his average scores. I want to make it more functional in allowing the user to input there name and scores and get all that info back. I may try to further this into a class average where it allows to input multiple individual names, scores, and average, print each one separately then showing the class average. This is a second thought though, as I need to have user input of grades and names first.
This is what I have so far.
I have a separate class to make some things simpler.
public class Student {
private String name;
private int numOfQuizzes;
private int totalScore;
public Student(String name){
this.name = name;
}
public String getName() {
return name;
}
public int getTotalScore() {
return totalScore;
}
public void addQuiz(int score) {
totalScore = totalScore + score;
numOfQuizzes++;
}
public double getAverageScore(){
return totalScore/(double)numOfQuizzes;
}
}
Then i have the main method:
public static void main(String[] args) {
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Student student = new Student(name);
student.addQuiz(96);
student.addQuiz(94);
student.addQuiz(93);
student.addQuiz(92);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
}
This is what it prints out currently:
What is your name? Tom
Students Name: Tom
Total Quiz Scores: 375
Average Quiz Score: 93.75
UPDATE:
This is what i have done so far. i added a loop and trying to use my student class but it doesn't seem to work with the array.
ArrayList<String> scores = new ArrayList<String>();
Scanner nameInput = new Scanner(System.in);
System.out.print("What is your name? ");
String name = nameInput.next();
Scanner scoreInput = new Scanner(System.in);
while (true) {
System.out.print("Please enter your scores (q to quit): ");
String q = scoreInput.nextLine();
scores.add(q);
if (q.equals("q")) {
scores.remove("q");
Student student = new Student(name);
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
break;
}
}
}
}
Since you are only learning the language just yet, I'll give you a few suggestions to send you on your way. You might want to use a while-loop to consistently ask the user for a new grade until they've given you an empty line or something. You can reuse your scanner to read the new grades and they can be converted to integers using Integer.parseInt. Hopefully this'll allow you to write your code further, it's already looking great :).
EDIT
There are several points which can be improved upon in your edited code. The following shows some of them (using import java.io.Console;):
Scanner inp = new Scanner(System.in);
// Request the name
System.out.print("What is your name? ");
String name = inp.nextLine();
// Create the student object
Student student = new Student(name);
// Ask for the grades
System.out.print("Please enter your scores (q to quit): ");
String grade = inp.nextLine();
while (!grade.equals("q")) {
// Convert the grade to an integer and pass it
student.addQuiz(Integer.parseInt(grade));
// Request a new grade
grade = inp.nextLine();
}
// Report the results
System.out.println("Students Name: " + student.getName());
System.out.println("Total Quiz Scores: " + student.getTotalScore());
System.out.println("Average Quiz Score: " + student.getAverageScore());
I'm learning object-oriented programming in a Java course, and I'm doing a project where a program creates three types of objects: Address, Date, and Employee. The program stores data of several employees and then displays the data in an array of type Employee.
I'm using four different classes: an Address class, a Date class, and an Employee Class, and an EmployeeTest class that creates the array.
Here is the Address class:
public class Address {
private String Street;
private String City;
private String State;
private int ZipCode;
public Address(String St, String Ci, String Sta, int Zip){
Street = St;
City = Ci;
State = Sta;
ZipCode = Zip;
}
public String getEmployeeAddress(){
return (Street + ", " + City + ", " + State + " " + ZipCode);
}
}
The Date Class:
public class Date {
private int Month;
private int Day;
private int Year;
public Date(int M, int D, int Y){
Month = M;
Day = D;
Year = Y;
}
public String getDateString(){
return (Month + "/" + Day + "/" + Year);
}
}
And, the Employee Class:
public class Employee {
private int EmployeeNum;
public void setEmployeeNum(int ENum){
EmployeeNum = ENum;
}
public int getNum(){
return EmployeeNum;
}
public String getDate(){
return Date.getDateString();
}
public String getName(){
return Name.getEmployeeName();
}
public String getAddress(){
return Address.getEmployeeAddress();
}
}
All of these classes are in the same package (I'm using Eclipse). The point of the Employee class is to create an object of type Employee and be able to get it's Address, Name, and HireDate using the Address, Name, and Date classes.
The place where the array comes into play is here:
import java.util.Scanner;
import java.lang.*;
public class EmployeeTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many employees will have their data stored today?");
int EmployeeAmount = Integer.parseInt(input.nextLine());
Employee [] EmployeeArray = new Employee[EmployeeAmount];
for (int i = 0; i < EmployeeArray.length; i ++){
System.out.print("What is employee " + (i+1) + "'s employee number?");
int EmployeeNumber = Integer.parseInt(input.nextLine());
EmployeeArray[i] = new Employee();
EmployeeArray[i].setEmployeeNum(EmployeeNumber);
System.out.println("What is the first name of employee " + EmployeeNumber + "?");
String EmployeeFirstName = input.nextLine();
System.out.println("What is the last name of employee " + EmployeeNumber + "?");
String EmployeeLastName = input.nextLine();
Name EmployeeName = new Name(EmployeeFirstName, EmployeeLastName);
System.out.println("Please enter the street address: ");
String StreetAddress = input.nextLine();
System.out.println("Please enter the name of the city: ");
String CityName = input.nextLine();
System.out.println("Please enter the two character code for the state: ");
String StateID = input.nextLine();
System.out.println("Please enter this address's zip code: ");
int ZipCode = Integer.parseInt(input.nextLine());
Address EmployeeAddress = new Address(StreetAddress, CityName, StateID, ZipCode);
System.out.println("Finally, what was the month(#) of the hire date?");
int Month = Integer.parseInt(input.nextLine());
System.out.println("What was the day(#)?");
int Day = Integer.parseInt(input.nextLine());
System.out.println("What was the year?");
int Year = Integer.parseInt(input.nextLine());
Date HireDate = new Date(Month, Day, Year);
}
for (int j = 0; j < EmployeeArray.length; j ++){
System.out.println("Employee number: " + EmployeeArray[j].getNum());
System.out.println("Employee Name: " + EmployeeArray[j].getName());
System.out.println("Employee Address: " + EmployeeArray[j].getAddress());
System.out.println("Employee Hiredate: " + EmployeeArray[j].getDate());
}
}
}
The program prompts the user for the number of employees to be stored in the array, then creates an Employee[] of size EmployeeAmount. The idea of the code is that for each Employee in the Array, all of the variables in the other classes are obtained: Employee Number, Employee Name (first and last), Address (Street Address, City, State Code, Zip Code), Hire Date (Month, Day, Year). After all this is obtained, the second for loop iterates through each Employee and displays the info.
The problem I am having is that in the Employeeclass, Eclipse gives me an error in the getDate(), getName(), and getAddress() methods. When I say for example, return Date.getDateString(), Eclipse says that I cannot make a static reference to a non-static method. It's solution is to make getDateString() static, and I tried this, but the problem is that by making all the methods and variables in the Address, Employee, and Date classes, the values are locked. Meaning that the same data will be displayed for all employees.
Here's what I mean. Below is a sample output if I made all the methods and variables static. The text in between the asterisks is what the user inputs.
How many employees will have their data stored today?**2**
What is employee 1's employee number?**1**
What is the first name of employee 1?
**Bob**
What is the last name of employee 1?
**Jones**
Please enter the street address:
**300 1st Avenue**
Please enter the name of the city:
**New York**
Please enter the two character code for the state:
**NY**
Please enter this address's zip code:
**10001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**1**
What was the year?
**2001**
What is employee 2's employee number?**2**
What is the first name of employee 2?
**Bobby**
What is the last name of employee 2?
**Robinson**
Please enter the street address:
**301 1st Avenue**
Please enter the name of the city:
**Los Angeles**
Please enter the two character code for the state:
**CA**
Please enter this address's zip code:
**90001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**2**
What was the year?
**2004**
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
By making all of the variables and methods static, the values are locked as shown, which makes the program useless. Does anyone have a solution to this problem? I need a way to display the information of each employee while referencing the methods in the other classes. Now, normally I would just create all the variables and methods under one class called Employee, but the assignment instructions specify that I need to make individual classes.
You are creating a Name, Address, and Date for each iteration of the for loop. But you have not way, nor do you set them on each Employee instance.
You need to add methods to set the values on each Employee and store the information. Something like this:
public class Employee {
private int employeeNum;
private Name name;
private Date hireDate;
private Address address;
public void setEmployeeNum(int eNum){
employeeNum = eNum;
}
public int getEmployeeNum(){
return employeeNum;
}
public void setHireDate(Date date){
this.hireDate = date;
}
public String getHireDate(){
return hireDate.getDateString();
}
public void setName(Name n){
this.name = n;
}
public String getName(){
return name.getEmployeeName();
}
public void setAddress(Address addy){
this.address = addy;
}
public String getAddress(){
return address.getEmployeeAddress();
}
}
Then in your for loop, set the values:
EmployeeArray[i].setName(EmployeeName);
EmployeeArray[i].setAddress(EmployeeAddress);
EmployeeArray[i].setHireDate(HireDate);
By the way, you should not capitalize variables, only classes.
Variables should be camel-cased.
I got a superclass Employee and subclasses of that (HourlyEmployee and CommissionEmployee) and a tester class.
When I run the program and take in user values, after it asks for hours/sales and calculates pay - the value given is 0.0. The pay is not being calculated correctly - or at all - why is this and how can I do it correctly?
abstract class Employee {
// Data members
private String firstName;
private String lastName;
private int employeeNumber;
private int numberOfEmployees;
protected int hours;
protected int sales;
protected double pay;
// Default constructor
public Employee() {
firstName = null;
lastName = null;
employeeNumber = 0;
numberOfEmployees = 0;
}
// Getter and setter methods
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(int employeeNumber) {
this.employeeNumber = employeeNumber;
}
public int getNumberOfEmployees() {
return numberOfEmployees;
}
public void setNumberOfEmployees(int numberOfEmployees) {
this.numberOfEmployees = numberOfEmployees;
}
// Abstract method to be implemented in sublcasses
public abstract void earnings();
#Override
public String toString(){
return "First Name: " + getFirstName() + "\n" + "Last Name: " + getLastName() + "\n" +
"Employee Number: " + getEmployeeNumber() + "\n" + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
public class HourlyEmployee extends Employee {
// Constructor
public HourlyEmployee() {
//Calls default constructor in superclass
super();
}
// Establish the amount of pay for hourly employees
int rate = 15;
// Override earnings method
#Override
public void earnings(){
pay = hours * rate;
}
// Return String representation of class
public String toString(){
return "First Name: " + getFirstName() + "Last Name: " + getLastName() +
"Employee Number: " + getEmployeeNumber() + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
public class CommissionEmployee extends Employee {
// Constructor
public CommissionEmployee() {
//Calls default constructor in superclass
super();
}
// Establish the amount of pay for hourly employees
double commission = 0.10;
// Override earnings method
#Override
public void earnings(){
pay = commission * sales;
}
// Return String representation of class
public String toString(){
return "First Name: " + getFirstName() + "Last Name: " + getLastName() +
"Employee Number: " + getEmployeeNumber() + "Number of Employees: "
+ getNumberOfEmployees();
}
}
`
import java.util.LinkedList;
import java.util.Scanner;
public class EmployeeTester {
public static void main(String[] args) {
// Protected double only visible in superclass and subclass.
// Must be declared again in tester class.
double pay;
int hours;
int sales;
// Create new LinkedList
LinkedList<Employee> employeeList = new LinkedList<>();
// Create Scanner obkect
Scanner keyboard = new Scanner(System.in);
char yes = 'y';
int x = 0;
while(yes == 'y' || yes == 'Y'){
// Declare & create a HourlyEmployee odject
HourlyEmployee employee1 = new HourlyEmployee();
employeeList.add(employee1);
System.out.print("Enter First Name: ");
String firstName = keyboard.next();
employee1.setFirstName(firstName);
employeeList.get(x).setFirstName(firstName);
System.out.print("Enter Last Name: ");
String lastName = keyboard.next();
employee1.setLastName(lastName);
employeeList.get(x).setLastName(lastName);
System.out.print("Enter Employee Number: ");
int employeeNumber = keyboard.nextInt();
employee1.setEmployeeNumber(employeeNumber);
employeeList.get(x).setEmployeeNumber(employeeNumber);
System.out.print("Enter Number of Employees: ");
int numberOfEmployees = keyboard.nextInt();
employee1.setNumberOfEmployees(numberOfEmployees);
employeeList.get(x).setNumberOfEmployees(numberOfEmployees);
System.out.print("Enter Hours Worked: ");
hours = keyboard.nextInt();
// Calculate earnings
employee1.earnings();
System.out.println(employee1.toString());
System.out.println("Total Earnings: " + employee1.pay);
x++; // increment x
System.out.print("Continue? [y/n] ");
yes = keyboard.next().charAt(0);
}
// Declare & create a CommissionEmployee odject
CommissionEmployee employee2 = new CommissionEmployee();
employeeList.add(employee2);
System.out.print("Enter First Name: ");
String firstName = keyboard.next();
employee2.setFirstName(firstName);
employeeList.get(x).setFirstName(firstName);
System.out.print("Enter Last Name: ");
String lastName = keyboard.next();
employee2.setLastName(lastName);
employeeList.get(x).setLastName(lastName);
System.out.print("Enter Employee Number: ");
int employeeNumber = keyboard.nextInt();
employee2.setEmployeeNumber(employeeNumber);
employeeList.get(x).setEmployeeNumber(employeeNumber);
System.out.print("Enter Number of Employees: ");
int numberOfEmployees = keyboard.nextInt();
employee2.setNumberOfEmployees(numberOfEmployees);
employeeList.get(x).setNumberOfEmployees(numberOfEmployees);
System.out.print("Enter Sales Made: ");
sales = keyboard.nextInt();
// Calculate earnings
employee2.earnings();
System.out.println(employee2.toString());
System.out.println("Total Earnings: " + employee2.pay);
x++; // increment x
System.out.print("Continue? [y/n] ");
yes = keyboard.next().charAt(0);
}
}
You need to set hours and sales to the employee objects, currently, they are 0, because, as int, both sales and hours get initialized to 0,
So, commission * sales will become 0 and hours * rate will become 0.
In EmployeeTester, set Hours to the HourlyEmployee object
System.out.print("Enter Hours Worked: ");
hours = keyboard.nextInt();
employee1.setHours(hours);
In EmployeeTester, set Sales to the CommissionEmployee object
System.out.print("Enter Sales Made: ");
sales = keyboard.nextInt();
employee2.setSales(sales);
You need to add setHours method in Employee
public void setHours(int hours) {
this.hours = hours;
}
call this method in EmployeeTester after getting hours from that.
This question already has answers here:
Java: .nextLine() and .nextDouble() differences
(2 answers)
Closed 8 years ago.
I am a beginner of Java. I am trying to create two Scanner objects from a class (which I have created by myself and there i also have created a constructor). I have initialized these two objects by the constructor call and later I want to update these two objects's information by obtaining data from user by Scanner class. When I am creating object by obtaining data from user by using Scanner object, I can create only one object and and the code for the second object are executing thoroughly without obtaining any data from the user. Thus I can create only one object and the code for second object is just displaying in the executing windows without obtaining any data.
Is it that I can't update the data of two objects by Scanner when they are already initialized by constructor call?
Here is the class code from where I want to create two object:
public class Employee {
//instance variables
String firstName;
String lastName;
double salary;
//constructor for three arguments
public Employee(String first_name, String last_name, double month_salary)
{
firstName = first_name;
lastName = last_name;
if(month_salary > 0) //make sure that the salary is not smaller than zero
{
salary = month_salary;
}
}//end of constructor
//set the value of the instance variables
//set first name
public void setFirstName(String first_name)
{
firstName = first_name;
}
//get first name
public String getFirstName()
{
return firstName;
}
//set last name
public void setLastName(String last_name)
{
lastName = last_name;
}
//get last name
public String getLastName()
{
return lastName;
}
//set salary
public void setSalary(double month_salary)
{
if(month_salary > 0) //make sure that the salary is not smaller than zero
{
salary = month_salary;
}
else salary = 0.00;
}
//get salary
public double getSalary()
{
return salary;
}
}
And here are the object's code
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee1 = new Employee("M", "R", 5000);
Employee employee2 = new Employee("T", "M", 6000);
System.out.println("Display the intial Employee's information\n");
//showing the Employee2's information
System.out.println("Displaying Employee1's information");
System.out.printf("First Name: %s\nLast Name: %s\nSalary: %.2f\n",
employee1.getFirstName(), employee1.getLastName(), employee1.getSalary());
System.out.println();
//showing the Employee2's information
System.out.println("Displaying Employee2's information");
System.out.printf("First Name: %s\nLast Name: %s\nSalary: %.2f\n",
employee2.getFirstName(), employee2.getLastName(), employee2.getSalary());
System.out.println();
//create an scanner object to get information from user
Scanner input = new Scanner(System.in);
//obtain employee's first name from user
System.out.print("Please enter the first name of employee1: ");
String fName1 = input.nextLine();
//set the first of employee1
employee1.setFirstName(fName1);
//obtain employee's last name from user
System.out.print("Please enter the last name of employee1: ");
String lName1 = input.nextLine();
//set the last of employee1
employee1.setLastName(lName1);
//set the salary employee1's
System.out.print("Please enter employee's salary: ");
double empl_salary1 = input.nextDouble();
//obtain the employe1's salary
employee1.setSalary(empl_salary1);
//display the updated employee1's information
System.out.println("Updated information of employee's information");
System.out.printf("First name :%s\nLast name: %s\nSalary: %.2f\n",
employee1.getFirstName(),employee1.getLastName(), employee1.getSalary());
//obtain employee2's first name from user
System.out.print("Please enter employee2'first name: ");
String fName2 = input.nextLine();
//set the first name of employee2
employee2.setFirstName(fName2);
//obtain employee's last name from user
System.out.print("Please enter the employee2's last name: ");
String lName2 = input.nextLine();
//set the last name of employee2
employee2.setLastName(lName2);
//obtain the salary employee2's
System.out.print("Please enter employee2's salary: ");
double empl_salary2 = input.nextDouble();
//set the employe1's salary
employee2.setSalary(empl_salary2);
}
}
I don't know where is the problem?
Thanks for your time and assistance!
Add input.nextLine(); just before obtaining data for second employee:
input.nextLine();
//obtain employee2's first name from user
System.out.print("Please enter employee2'first name: ");
String fName2 = input.nextLine();
It is because input.nextDouble(); "consumes" only double value, leaving the newline character you entered "unconsumed".