I have been trying to create a small program that prompts the user for input that takes an employee name and salary adds it to an arrayList, then displays options on the screen(e.g 0: quit, 1: add, 2: display), reads the input then proceeds based on the input.Displaying would just be(e.g Last Name: Smith Salary: £14000. Just need some help to point me in the right direction. I currently have 3 classes Employee, Employee List and Employee Test.
This class prompts the user input.
import java.util.Scanner;
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
Scanner inputValues = new Scanner(System.in);
System.out.print("Enter employee last name: ");
Last_Name = inputValues.next();
System.out.print("Enter Employee Salary: " + "£");
Salary = inputValues.nextInt();
}
public void Display(){
System.out.printf("Name: " + Last_Name + " " + "Salary: " + Salary);
System.out.println("\n");
}
}
This class is supposed to be adding the employees to an arraylist but im not sure if im doing it correctly.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EmployeeList extends Employee{
private List <Employee> employee = new ArrayList<Employee>();
public EmployeeList(Employee person) {
employee.add(person);
}
public void DisplayEmployees(){
System.out.println("Employee:" + employee.size());
displayList(employee);
}
public static void displayList(List employee) {
}
}
This is where the main method is
import java.util.Scanner;
public class EmployeeTest {
public static void main(String[] args) {
Employee employee = new Employee();
employee.Display();
EmployeeList empList = new EmployeeList(employee);
empList.DisplayEmployees();
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String employees = scanner.next();
/* if (employees.equals("1")){
//not sure how to go back to displaying the user prompts
break;
} */
}
}
Few tips I can think of:
EmployeeList should not extend Employee. The main rule of OOP is that class A extends class B if B is a A. This is clearly not the case here - employeeList is not an employee, it's a list of employees (In my mind you don't need a class for this, just List<Employee>)
I'd separate the logic from the data. meaning - Employee class should only hold the employee's data, not deal with scanning and getting the input from the user. the constructor should be simple in my mind, something like:
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
The logic of getting the data should be outside of this class, either in an EmployeeHandler or in the main itself. Since you put it inside the employee, you are having troubles continuing when some of the logic is in the employee and some in the main.
the high-level code should be something like (I'll leave the details to you):
show the menu options to the user
if he wants to add user, get input for both variables, create the employee object and add it to the list
if he wants to display, go over the list and print (the printing can be done overriding toString in Employee class)
if he wants to quit, finish
continue this loop until he wants to quit
public class Employee {
private String Last_Name;
private int Salary;
public Employee(){
public String getLName(){
return Last_Name;
}
public void setLName(){
this.Last_Name = Last_Name;
}
public int getSalary(){
return salary;
}
public void setSalary(){
this.salary = salary;
}
}
}
then in your main method you can create the employee object.
public static void main(String[] args){
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
employee.setLName = scanner.next();
employee.setSalary = scanner.nextInt();
}
If i were you I would just make an arraylist to hold all employees. I would prompt the input option for x amount of times and add to the end of the arraylist. the arraylist would be created as so
ArrayList<Employee> employeeList = new ArrayList<Employee>();
to add to it use add
employeeList.add(employee);
This should be able to get you started
EDIT:
OOPS, made several mistakes. edit with the following. Note that it is employee.setLastName(value) because the method setLastName is part of the employee class and it must be passed a value because we have defined that in the employee class.
Employee employee = new Employee();
Scanner scanner = new Scanner(System.in);
String tempName = scanner.next();
int tempSalary = scanner.nextInt();
employee.setLastName(tempName);
employee.setSalary(tempSalary);
EDIT 2:
try to print arraylists as follows. didnt test it. let me know how it works.
for (int i = 0; i< employeelist.size(); i++){
Employee temp = values.get(i);
System.out.println("Last Name: " + temp.getLname() + "Salary: " + temp.getSalary());
}
I modified my employee class to look like this:
public class Employee {
public String lastName;
private int salary;
public Employee(){
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
#Override
public String toString(){
return "Employee Last Name: " + lastName + "\n" + "Employee Salary: " + salary;
}
}
I have modified my EmployeeTest class:
This is my EmployeeTest class:
import java.util.ArrayList;
import java.util.Scanner;
public class EmployeeTest {
static ArrayList<Employee> employeeList = new ArrayList<Employee>();
public static void main(String[] args) {
for(int i=0;i<5;i++){
addEmployees(employeeList);
}
System.out.println(employeeList.toArray());
}
public static void addEmployees(ArrayList<Employee> employeeList){
Scanner scanner = new Scanner(System.in);
System.out.println("0: quit, 1: add, 2: display");
String options = scanner.next();
if(options.equals("1")){
System.out.print("Enter employee last name: ");
String lastname = scanner.next();
System.out.print("Enter Employee Salary: " + "£");
int salary = scanner.nextInt();
Employee employee = new Employee();
EmployeeList.add(employee);
}
else if(options.equals("2")){
for (Employee employee : employeeList){
/*System.out.println("Name: " + employee.getLastName() + ", " + "Salary: " + employee.getSalary());*/
System.out.println(employee);
}
}
else{
System.exit(0);
}
}
}
However when i press 2 as my options it doesn't display what is in my arraylist.
I had read that a toString method is used to get those details so i could print them to the screen. And that using this for loop gets each item in the list to display them. Am i missing something here?. Apologies for this dragging on a bit, im just wanting this to work.
Related
I checked the code and saving data to the HashMap is correct, when typing ADD. Then after choosing option FIND I can get to the dedicated function but the method is unable to show me found object even if it is correct 100%.
Please check this code out and tell me why it does not find right objects in "public void showInfo(String name, String secondName)" for class Company that is sparked by TYPING "FIND" in class CompanyApp
import java.util.InputMismatchException;
import java.util.Objects;
import java.util.Scanner;
public class CompanyApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
options[] values = options.values();
int choose;
int EXIT_NR = 2;
Company ref = new Company();
do {
System.out.println("Available options: ");
for (options one : values) {
System.out.println(one.getDescription() + " - " + one.name());
}
System.out.println("Choose one: ");
try {
choose = options.valueOf(in.nextLine()).ordinal();
if (Objects.equals(EXIT_NR, choose)) break;
if (choose < 0 || choose >= options.values().length) {
throw new IllegalArgumentException("Choose 0, 1 or 2!");
}
options(choose);
} catch (InputMismatchException e) {
System.out.println("Choose a number ");
}
} while (1 == 1);
}
static void options(int choose){
Company ref = new Company();
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to
find: ");
String secondName2 = info.nextLine();
ref.showInfo(name2, secondName2);
break;
}
}
}
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
public class Company {
private Map<String, Employee> map = new HashMap<>();
public void add(Employee employee){
String key = employee.getName() + " " + employee.getSecondName();
if(!map.containsKey(key)){
map.put(key, employee);
System.out.println("Added object to map");}
}
public void showInfo(String name, String secondName){
String key = name + " " + secondName;
System.out.println("in showinfo method");
if(map.containsKey(key)){
System.out.println("found an object");
Employee employee = map.get(key);
System.out.println(employee.getName());
}}}
enum options {
ADD("Add employee "), FIND("Find employee"), EXIT("Exit program");
private String description;
options(String description) {
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public String toString() {
return "options{" +
"description='" + description + '\'' +
'}';
}
}
String name;
String secondName;
double salary;
public Employee(String name, String secondName, double salary) {
this.name = name;
this.secondName = secondName;
this.salary = salary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", secondName='" + secondName + '\'' +
", salary=" + salary +
'}';
}
}
The problem is in the method static void options(int choose). You need to pass the Company-Object and use it there like this:
Call from main method (ref is the Company-Object you create in the main method)
options(choose, ref);
The options-method with the Company as second parameter:
static void options(int choose, Company ref){
Scanner info = new Scanner(System.in);
switch (choose){
case 0:
System.out.println("Type in the name of the worker: ");
String name = info.nextLine();
System.out.println("Type in the second name of the worker: ");
String secondName = info.nextLine();
System.out.println("Type in the salary: ");
double salary = info.nextDouble();
info.nextLine();
//use the passed Company here
ref.add(new Employee(name, secondName, salary));
break;
case 1:
System.out.println("Type in the name of the worker you want to find: ");
String name2 = info.nextLine();
System.out.println("Type in the second name of the worker you want to find: ");
String secondName2 = info.nextLine();
//and here
ref.showInfo(name2, secondName2);
break;
}
}
Explanation what is happening in your code
As mentioned, the problem is in the method static void options(int choose).
Here you create a new Company-Object which is not passed in any way to the main method.
This is what happens, when you use ADD and a FIND afterwards:
Call options from main method with ADD
new Company-Object is created in options
new Employee-Object is added to the Company from the previous point
the method ends -> the created Company-Object is "thrown away" (eligible for Garbage Collection)
Call options from main method with FIND
new Company-Object is created in options(therefore no Employees in it)
no Employee can be found, because there is no entry in the map of the newly created Company
The map is empty at the time when you're trying to get the data from it using FIND option. The reason for that is you recreate the Company object in the options method:
Company ref = new Company();
At the same time also the map is recreated so there are no records inside.
Also, the Company object in the main method is not used.
Im currently learning java and im trying to create an Employee management program that stores employee records into an array and allow management to manipulate the array and print any employee reports. So I create a menu and ten employee objects which got stored in an array...now what I want to do is allow the user to input employee details through the menu and that information will be stored inside the objects and I want the user to be able to search for an employee by their title and also display only male of female employees.
I first started with my employee class where has my modifers
public class Employee{
int emp_id=0;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public Employee(){}
public Employee(int emp_id,String fname,String lname,String dob,String gender,String address,String title,String dateHired,String
department,int hoursWorked,double rateOfpay,int leaveDays,double carAllowance,double monthlyGratuity,double taxRate){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
this.dob=dob;
this.gender=gender;
this.address=address;
this.title=title;
this.dateHired=dateHired;
this.department=department;
this.hoursWorked=hoursWorked;
this.rateOfpay=rateOfpay;
this.leaveDays=leaveDays;
this.carAllowance=carAllowance;
this.monthlyGratuity=monthlyGratuity;
this.taxRate=taxRate;
}
public Employee(int emp_id,String fname,String lname){
this.emp_id=emp_id;
this.fname=fname;
this.lname=lname;
}
public void setEmployeeId(int emp_id){
this.emp_id=emp_id;
}
public void setFirstName(String fname){
this.fname=fname;
}
public void setLastName(String lname){
this.lname=lname;
}
public void setDateOfBirth(String dob){
this.dob=dob;
}
public void setGender(String gender){
this.gender=gender;
}
public void setAddress(String address){
this.address=address;
}
public void setTitle(String title){
this.title=title;
}
public void setDateHired(String dateHired){
this.dateHired=dateHired;
}
public void setDepartment(String department){
this.department=department;
}
public void setHoursWorked(int hoursWorked){
this.hoursWorked=hoursWorked;
}
public void setRateOfPay(double rateOfpay){
this.rateOfpay=rateOfpay;
}
public void setLeaveDays(int leaveDays){
this.leaveDays=leaveDays;
}
public void setCarAllowance(double carAllowance){
this.carAllowance=carAllowance;
}
public void setMonthlyGratuity(double monthlyGratuity){
this.monthlyGratuity=monthlyGratuity;
}
public void setTaxRate(double taxRate){
this.taxRate=taxRate;
}
public int getEmployeeId(){
return emp_id;
}
public String getFirstName(){
return fname;
}
public String getLastName(){
return lname;
}
public String getDateOfBirth(){
return dob;
}
public String getGender(){
return gender;
}
public String getAddress(){
return address;
}
public String getTitle(){
return title;
}
public String getDateHired(){
return dateHired;
}
public String getDepartment(){
return department;
}
public int getHoursWorked(){
return hoursWorked;
}
public double getRateOfPay(){
return rateOfpay;
}
public int getLeaveDays(){
return leaveDays;
}
public double getCarAllowance(){
return carAllowance;
}
public double getMonthlyGratuity(){
return monthlyGratuity;
}
public double getTaxRate(){
return taxRate;
}
}
Then created the objects and arrays in the class below
import java.util.Scanner;
public class employeeArray extends Employee{
private static Employee employees[] = new Employee[10];
static Scanner input=null;
String fname="pebbles";
String lname=null;
String dob=null;
String gender=null;
int emp_id=0;
String address=null;
String title=null;
String dateHired=null;
String department=null;
int hoursWorked=0;
double rateOfpay=0.0;
int leaveDays=0;
double carAllowance=0.0;
double monthlyGratuity=0.0;
double taxRate=0.0;
public static Employee e1=new Employee(12345,"Aobakwe","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
public static Employee e2=new Employee();
public static Employee e3=new Employee();
public static Employee e4=new Employee();
public static Employee e5=new Employee();
public static Employee e6=new Employee();
public static Employee e7=new Employee();
public static Employee e8=new Employee();
public static Employee e9=new Employee();
public static Employee e10=new Employee();
public static void main(String args[]){
input=new Scanner(System.in);
Employee e1=new Employee(12345," ","Mothabi","26/07/1990","Male","Private 009 Masunga","CEO",
"06/02/2008","Finance",500,50.0,10,100.0,1500,5.1);
Employee e2=new Employee();
Employee e3=new Employee();
Employee e4=new Employee();
Employee e5=new Employee();
Employee e6=new Employee();
Employee e7=new Employee();
Employee e8=new Employee();
Employee e9=new Employee();
Employee e10=new Employee();
employees[0]=e1;
employees[1]=e2;
employees[2]=e3;
employees[3]=e4;
employees[4]=e5;
employees[5]=e6;
employees[6]=e7;
employees[7]=e8;
employees[8]=e9;
employees[9]=e10;
//ENTER NAME
System.out.println("Enter name");
String fname=input.next();
e2.setFirstName(fname);
//ENTER LAST NAME
System.out.println("Enter surname");
String lname=input.next();
e2.setLastName(lname);
//ENTER DATE OF BIRTH
System.out.println("Enter date of birth");
String dob=input.next();
e2.setDateOfBirth(dob);
//ENTER GENDER
System.out.println("Enter Gender");
String gender=input.next();
e2.setGender(gender);
//ENTER EMPLOYEE ID
System.out.println("Enter Employee Id");
int emp_id=input.nextInt();
e2.setEmployeeId(emp_id);
//ENTER ADDRESS
System.out.println("Enter Address");
String address=input.next();
e2.setAddress(address);
//ENTER TITLE
System.out.println("Enter Employee Title");
String title=input.next();
e2.setTitle(title);
//ENTER DATE HIRED
System.out.println("Enter Date Hired");
String dateHired=input.next();
e2.setDateHired(dateHired);
//ENTER DEPARTMENT
System.out.println("Enter Department");
String department=input.next();
e2.setDepartment(department);
//ENTER HOURS WORKED
System.out.println("Enter Hours Worked");
int hoursWorked=input.nextInt();
e2.setHoursWorked(hoursWorked);
//ENTER RATE OF PAY
System.out.println("Enter Rate Of Pay");
double rateOfpay=input.nextDouble();
e2.setRateOfPay(rateOfpay);
//ENTER LEAVE DAYS
System.out.println("Enter Leave Days");
int leaveDays=input.nextInt();
e2.setLeaveDays(leaveDays);
//ENTER CAR ALLOWANCE
System.out.println("Enter Car Allowance");
double carAllowance=input.nextDouble();
e2.setCarAllowance(carAllowance);
//ENTER MONTHLY GRATUITY
System.out.println("Enter Monthly Gratuity");
double monthlyGratuity=input.nextDouble();
e2.setMonthlyGratuity(monthlyGratuity);
//ENTER TAX RATE
System.out.println("Enter Tax Rate");
double taxRate=input.nextDouble();
e2.setTaxRate(taxRate);
//DISPLAY RESULTS
System.out.println(e2.getFirstName());
System.out.println(e2.getLastName());
System.out.println(e2.getDateOfBirth());
System.out.println(e2.getGender());
System.out.println(e2.getEmployeeId());
System.out.println(e2.getAddress());
System.out.println(e2.getTitle());
System.out.println(e2.getDateHired());
System.out.println(e2.getDepartment());
System.out.println(e2.getHoursWorked());
System.out.println(e2.getRateOfPay());
System.out.println(e2.getLeaveDays());
System.out.println(e2.getCarAllowance());
System.out.println(e2.getMonthlyGratuity());
System.out.println(e2.getTaxRate());*/
}
static void mainMenu(){
System.out.println(
"Select an option\n"+
"1)Add Employee Records\n"+
"2) display only male of female employees\n"+
"3) display all employees and their gross salaries\n"+
"4) search for an employee and display salary calculated.\n");
}
}
and lastly here is my tester class which displays the menu and allows the user to select an option
import java.util.Scanner;
public class empTester extends employeeArray{
static Scanner input=null;
public static void main(String args[]){
input=new Scanner(System.in);
mainMenu();
int choice=input.nextInt();
if(choice==1){
menuAdd();
int option=input.nextInt();
if(option==1){EmployeeCreation();}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==2){
menuDisplay();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){System.out.println("It works number 3");}
else if(option==4){System.out.println("It works number 4");}
else if(option==5){mainMenu();}
}
else if(choice==3){
menuSearch();
int option=input.nextInt();
if(option==1){System.out.println("It works number 1");}
else if(option==2){System.out.println("It works number 2");}
else if(option==3){mainMenu();}
}
else if(choice==4){
System.out.println("This is the About Section");
}
else if(choice==5){
System.out.println("Ending Program");
System.exit(0);
}
}
}
Yeah so I managed to find a way to enable the user to add an employee record and display details added. Im having trouble creating methods for other functions stated in the menu without having to create new objects.
I think you need a static list.
public static List<Employee> employees = new ArrayList<>();`
public void addEmployee() {
Employee employee = new Employee();
input=new Scanner(System.in);
String fname=input.next();
employee.setFirstName(fname);
.
.
. and others setters...
eployees.add(employee);
}
And read about toString() method to display object details.
toString(), ArrayList, static variable
Here are a few suggestions. The Employee class seems ok. Note that you do not need to supply default values for variables if they are the same as the type's default value. Ex:
String lname=null;
int hoursWorked=0;
double rateOfpay=0.0;
Is the same as
String lname;
int hoursWorked;
double rateOfpay;
You might consider adding a function to the class to read data from a Scanner:
class Employee {
....
boolean readFromIn(Scanner input)
{
//ENTER NAME
System.out.println("Enter name");
fname = input.next();
//ENTER LAST NAME
System.out.println("Enter surname");
lname = input.next();
etc....
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(lname);
....fill in rest
return sb.toString();
}
....
}
The entire employeeArray class seems necessary. But if you want that, there's no need for the temporary variables e1, e2, etc. You have the array, you can add directly to it. A loop helps here:
public class EmployeeArray /* extends Employee - does not extend Employee */
{
private static Employee employees[] = new Employee[10]; // why static?
public static void createEmployees()
{
Scanner in = new Scanner(System.in);
for (int i = 0; i < employees.length; i++) {
employees[i] = new Employee();
employees[i].readFromIn(in);
}
}
public static Employee getEmployee(int index)
{
if (index < 0 || index >= employees.length) {
throw new ArrayIndexOutOfBoundsException();
}
return employees[i];
}
}
I have written the code this expected output:
Sample input :
Enter the passenger name:
Priya
Enter the gender(M or F / m or f):
F
Enter the age:
61
Enter the ticket no:
140
Enter the ticket price:
500.0
Sample Output 1 :
Ticket no:143
Passenger Name:Priya
Price of a ticket : 500.0
Total Amount : 375.0
I have to change the total amount value based on the age and gender for which I have written function.
My code:
Person.java
public class Person {
private String name;
private char gender;
private int age;
public void setName(String name ){
this.name = name;
}
public void setGender(char gender){
this.gender = gender ;
}
public void setAge(int age ){
this.age = age;
}
public String getName(){
return this.name;
}
public char getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
}
BusTicket.java
public class BusTicket {
private int ticketNo;
private float ticketPrice;
private float totalAmount;
Person person = new Person();
int age = person.getAge();
char g = person.getGender();
public void setTicketNo(int ticketNo){
this.ticketNo = ticketNo;
}
public void setTicketPrice(float ticketPrice){
this.ticketPrice = ticketPrice;
}
public void setTotalAmount(float totalAmount){
this.totalAmount = totalAmount;
}
public void calculateTotal()
{
if(age<16)
{
totalAmount = ticketPrice/2;
setTotalAmount(totalAmount);
}
else if(age>=60)
{
totalAmount = 3*(ticketPrice/4);
setTotalAmount(totalAmount);
}
else if(g == 'f'|| g== 'F')
{
totalAmount = 9*(ticketPrice/10);
setTotalAmount(totalAmount);
}
else{
setTotalAmount(ticketPrice);
}
}
public int getTicketNo(){
return this.ticketNo;
}
public float getTicketPrice(){
return this.ticketPrice;
}
public float getTotalAmount(){
return this.totalAmount;
}
}
TestMain.java
import java.util.Scanner;
public class TestMain {
public static BusTicket getTicketDetails()
{
Scanner sc = new Scanner(System.in);
BusTicket bt = new BusTicket();
System.out.println("Enter the ticket no:");
bt.setTicketNo(sc.nextInt());
System.out.println("Enter the ticket price:");
bt.setTicketPrice(sc.nextFloat());
return bt;
}
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
Person p = new Person();
BusTicket bt;
System.out.println("Enter the passenger name:");
p.setName(sc.nextLine());
System.out.println("Enter the gender(M or F/ m or f):");
p.setGender(sc.next().charAt(0));
System.out.println("Enter the age:");
p.setAge(sc.nextInt());
bt = getTicketDetails();
System.out.println("Ticket no:"+bt.getTicketNo());
System.out.println("Passenger Name:"+p.getName());
System.out.println("Price of a ticket : "+bt.getTicketPrice());
System.out.println("Total Amount : "+bt.getTotalAmount());
}
}
But my TotalAmount value is always coming 0.0, it is not getting updated.
And some test cases are failed please help to resolve them:
Fail 1 -
Incorrect access specifier/modifier for person -Should be a [private]
Fail 2 -
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method setPerson is correct
Fail 3-
Check whether the signature(Returntype/Argument/AccessSpecifier/MethodName) of the method getPerson is correct
Please Help
Thanks
You need to call calculateTotal to update totalAmount. Otherwise, it will be always 0.0.
...
System.out.println("Price of a ticket : "+bt.getTicketPrice());
bt.calculateTotal(); // Add this line
System.out.println("Total Amount : "+bt.getTotalAmount());
In your BusTicket class a new Person object is assigned to Person attribute and then you are trying to get age and gender details from that newly created Person object, but at this moment Person's age and gender are not populated yet.
Person person = new Person();
int age = person.getAge();
That's why you are getting 0. What should ideally happen is, you should pass the person object created using the input details to the BusTicket class and populate the BusTicket's person attribute with that person.For now I ll tell just that. :)
Give a try :)
In your BusTicket class, create a getter and setter for the Person object, and set the value from the main method.
This my code, I just print screen it because I'm getting an error while posting this code
how to make this program to store personal information and store another person information.
Instead of making a do-while, then you could write a separate method for it and call it when needed
public void gatherUserInformation()
{
System.out.println("Enter name:");
...
System.out.println("Enter last name ");
...
}
Then call this method from your main method, and then make the first person print out.
Then in your main method, make this right after:
if(scan.nextInt() == 1)
{
gatherUserInformation()
}
You can create Person class like:
public class Person{
private String name;
private String lastname;
// void cons
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getLastname(){
return lastname;
}
public void setLastname(String lastname){
this.lastname= lastname;
}
}
And after that you change our main to work with that:
ArrayList<Person> pList = new ArrayList<>();
At the beginning of each loop:
Person person = new Person(); // void cons
And after that you can add 'person' in pList, use get methods to get object values and set methods to change that values:
person.setName(scan.next());
To show person name:
person.getName();
To show pList, open another loop:
int i = 1;
for ( Person p : pList ){
System.out.println("Person " + i + " name: " + p.getName());
System.out.println("Person " + i + " lastname: " + p.getLastname());
System.out,println(" ----------------------------------------- ");
i++;
}
I do not test but I think that's it
Good Lucky
I'm working on my intro to programming assignment. Previously I created a program that models an employee using classes for Address Name and Date. This week the assignment is adding subclasses for Hourly and Salaried employees. To start with I tried making my employee class abstract, but when I do that, I get an error in my ArrayList "Cannot instantiate the type Employee (I put in a comment that shows where this error is)" I have posted my code below-- If anyone could give me any suggestions I would really appreciate it I've been struggling with what to do for hours.
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public abstract class Employee
{
private int id;
private Name name;
private Address address;
private Date date;
Employee (int id, Name name, Address address, Date date)
{
setId(id);
setName(name);
setAddress(address);
setDate(date);
}
//Setter
public void setId(int id)
{
this.id = id;
}
public void setName(Name name)
{
this.name = name;
}
public void setAddress(Address address)
{
this.address = address;
}
public void setDate(Date date)
{
this.date = date;
}
//Getter
public int getId()
{
return id;
}
public Name getName()
{
return name;
}
public Address getAddress()
{
return address;
}
public Date getDate()
{
return date;
}
public String toString()
{
return "ID: " +getId()+ "Name: " +getName()+ "Address: " +getAddress()+ "Hire Date: "+ getDate();
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
// Ask user for number of employees; create array of appropriate size
System.out.println("Enter the number of employees: ");
int numEmployees = input.nextInt();
List<Employee> employees = new ArrayList<>();
// Read information on individual employees.
for (int i = 0; i < numEmployees; i++)
{
System.out.println("Enter the employee ID number: " );
int id = input.nextInt();
input.nextLine(); //without this the scanner skips
System.out.println("Enter the first name of the employee: " );
String firstName = input.nextLine();
System.out.println("Enter the last name of the employee: " );
String lastName = input.nextLine();
System.out.println("Enter the street address of the employee: " );
String street = input.nextLine();
System.out.println("Enter the city where the employee resides: " );
String city = input.nextLine();
System.out.println("Enter the state where the employee resides (two letter abbreviation): " );
String state = input.nextLine();
System.out.println("Enter the zip code of the employee: " );
String zip = input.nextLine();
System.out.println("Enter the month the employee was hired (1-12): " );
int month = input.nextInt();
System.out.println("Enter the day the employee was hired (1-31): " );
int day = input.nextInt();
System.out.println("Enter the year the employee was hired (1900-2020): " );
int year = input.nextInt();
input.nextLine(); //without this the scanner skips to last name
Name name = new Name(firstName, lastName);
Address address = new Address(street, city, state, zip);
Date date = new Date(month, day, year);
//this is where I get the error
Employee employee = new Employee(id, name, address, date);
employees.add(employee);
}
/**
* Print out information on all the employees
* Use Foreach loop to iterate through ArrayList
**/
for(Employee employee : employees)
{
System.out.print("ID:" + employee.getId() + " ");
System.out.print("Name:" + employee.getName().getFirstName() + " ");
System.out.println(employee.getName().getLastName());
System.out.print("Address:" + employee.getAddress().getStreet() + " ");
System.out.print(employee.getAddress().getCity() + " ");
System.out.print(employee.getAddress().getState() + " ");
System.out.println(employee.getAddress().getZip());
System.out.print("Hire Date: " + employee.getDate().getMonth() + "/");
System.out.print(employee.getDate().getDay() + "/");
System.out.println(employee.getDate().getYear());
System.out.println();
}
input.close();
}
}
You cannot instantiate abstract classes in Java. You can, however, instantiate a quick non-abstract subclass from them. In this subclass you'd of course need to implement all methods that are abstract as well
abstract class Foo {
...
}
public static void main(String args[]) {
Foo foo = new Foo(); //Can't do
Foo foo = new Foo() {}; // this will work, as long as Foo has a null constructor; if Foo has abstract methods, make sure to define them concretely within the { ... } block
}
Usually abstract classes are used to provide the basic data/methods to subclasses.
You cannot instantiate an object of abstract class.*
It's just a level of program abstraction and a good practice to create a hierarchical class structure.
*But you may use a reference to abstract class for creating an object of a concrete type.
AbstractClass obj = new ConcreteClass(); // if ConcreteClass extends AbstractClass
Making a class abstract usually means that it will be used as a parent class for subclasses that need to implement the same methods. Abstract classes cannot be instantiated. Once you have created your required subclasses, HourlyEmployee and SalariedEmployee, you'll be able to define a new object like this:
Employee employee = new HourlyEmployee();
or
Employee employee = new SalariedEmployee();
Here's a great explanation regarding abstract classes: https://stackoverflow.com/a/1320887/6062407