Here is the assignment I"m supposed to complete:
Write a program that models an employee. An employee has an employee number, a name, an address, and a hire date. A name consists of a first name and a last name. An address consists of a street, a city, a state (2 characters), and a 5-digit zip code. A date consists of an integer month, day and year.
Use an Employee class, a Name class, an Address class, and a Date class in your solution.
Your program should prompt the user to enter data for several employees and then display that data. The number of employees to store data for shall be entered from the command line.
What I'm confused about is how to use all the different classes for storing info.
Here is my code (sorry this post is so dang long)
import java.util.Scanner;
public class unitTenDemo
{
public static void main ( String [ ] args )
{
Scanner input = new Scanner ( System.in );
System.out.print ( "Enter the number of employees" );
System.out.println ( "\t" );
int employees = input.nextInt ( );
for ( int count = 0; count < employees; count ++ )
{
System.out.print ( "Enter the employees' numbers" );
int employeeNumber = input.nextInt ( );
System.out.println ( );
System.out.println ( "The number is " +employeeNumber );
System.out.println ( );
}
}
}
//that was the actual output code
//here's the constructor that I'm stuck on
public class unitTen
{
int employeeNumber;
public int Employee ( int empNum )
{
employeeNumber = empNum;
}
string employeeName;
public void Name ( string empName )
{
employeeName = empName;
}
string street;
string city;
string state;
int zipCode;
}
Don't put everything into the constructor. It's okay to write a constructor that builds an object that is not fully initialized. You can organize your program as follows:
Find out how many Employee objects there will be (user input)
Create an array of Employee objects of the appropriate length
For each element of the array, assign a new Employee to that element
For each element of the array, prompt the user for each piece of data needed to properly initialize the Employee.
The last step (which deals with only one Employee at a time) will break down into a lot of details, since each Employee object has a lot of information. Just go through all the elements systematically.
This code won't compile at all. Yopu have declaired int as return type and not returning anything from the method.
public int Employee ( int empNum )
{
employeeNumber = empNum;
}
In addition to the answer pointed to by #Ted , you should modify your Employee class accordingly and then invoke the constructors as you please.
public class Employee // you should change the name of class to Employee
{
int employeeNumber;
public Employee(){}; // default constructor to create empty Employee objects
public Employee ( int empNum ) // constructor cannot have any return type
{
employeeNumber = empNum;
}
string employeeName;
public Employee( string empName, int empNum ) // you can create multiple constructors with different parameters.
{
employeeName = empName;
employeeNumber = empNum;
}
string street;
string city;
string state;
int zipCode;
// you can create getters and setters for these fields
}
Related
I'm creating a banking app and I need to generate a customer number starting from number 1, keeping track of the number so that it won't repeat itself each time I enter the loop and store it into an int variable that I can use to collect the value and pass it to the customerNumber variable outside the loop. I've tried a few things like arraylists and arrays, but I was getting troubles in passing the values to the variable I wanted. Thanks in advance and sorry for my terrible noobishness...I'm new in programming... Here's what I've got so far:
import java.util.ArrayList;
public class Bank{
public void addCustomer(String name, int telephone, String email, String profession) {
ArrayList customerList = new ArrayList();
Customer customer = new Customer();
customerList.add(customer);
}
}
public class Customer{
private String name;
private int telephone;
private String email;
private String profession;
private int customerNumber;
public Customer() {
}
}
public class Menu {
Scanner sc = new Scanner(System.in);
Bank bank = new Bank();
private void createCustomer() {
String name, email, profession;
int telephone, customerNumber;
System.out.println("Enter the customer's number: ");
name = sc.nextLine();
System.out.println("Enter the customer's telephone: ");
telephone = sc.nextInt();
System.out.println("Enter the customer's email: ");
email = sc.nextLine();
System.out.println("Enter the customer's profession: ");
profession = sc.nextLine();
bank.addCustomer(name, telephone, email, profession);
}
}
One thing you can do is create a singleton class, and request a number each time you need one. The singleton class keeps a list of the numbers that have been used already, and thus can return a number that has not been used before.
If you need also to generate new numbers after your application is restarted, then you can store all numbers in a file, and read that file whenever needed.
A singleton class, is a class that can have max 1 instance. You can achieve this by making the constructor private, and creating a public static method (usually called something like getInstance() ) to get an instance of this class. This getInstance() returns the ref to the only instance, and if no instance was created yet, it first creates one.
Then, this only instance knows all account numbers in use (inyour case), regardless how often an instance of this class is requested.
The responsibility of this class is to maintain the account nrs: create a nr, print them, save them, read them, ...
Example:
private AccoutnNr singleInstance;
private AccountNr(){
}
public AccountNr getInstance(){
if (singleInstance == null) {
singleInstance = new AccountNr();
}
return singleInstance;
}
public int getAccountNr{
// do whatever is needed to create an account nr
}
more methods if you need to do more than creating account numbers
I have two constructors for Student and am trying to use both of them with one object. But I should be doing it wrong because my output is not what I expect it to be.
Output:
School: null
Grade Level: 0
Intended Major: null
Student's ID number is: 154324
Student's name: Sam Bay
Student's GPA: 3.56
Code for class definition:
public class Student
{
private int id, gradeLevel;
private String name, school, major;
private double gpa;
//constructor to initialize the instance variables of student object
public Student(int id, String name, double gpa)
{
this.id = id;
this.name = name;
this.gpa = gpa;
}
public Student(int gradeLevel, String school, String major)
{
this.gradeLevel = gradeLevel;
this.school = school;
this.major = major;
}
//toString() to display the attributions of the student object
public String toString()
{
return "School: " + school +
"\nGrade Level: " + gradeLevel +
"\nIntended Major: " + major + "\n" +
"\nStudent's ID number is: " + id +
"\nStudent's name: " + name +
"\nStudent's GPA: " + gpa;
}
}//end class
code for main:
public class StudentDrive
{
public static void main(String [] args)
{
//creating student objects
Student sam = new Student(12, "Alpha High School", "Biology");
sam = new Student(154324, "Sam Bay", 3.56);
System.out.println(sam);
}
}
It seems like I've initialized the first part but I get null and 0??!!!
You can't use two constructors simultaneously on a single object.
In your code:
Student sam = new Student(12, "Alpha High School", "Biology");
creates a new Student object and assigns its reference to the variable sam.
On your next line:
sam = new Student(154324, "Sam Bay", 3.56);
This creates another Student object, separate from the first, and reassigns sam to refer to it instead. In the process, you end up orphaning the original Student and leave it open to garbage collection.
What you really want to do is either pass all data required for by a Student through a single constructor, or provide getters/setters (e.g. setGradeLevel(int level)) and a layer of exceptions that prevent methods from accessing a Student object until all fields are filled. The first option is generally more sound.
For example, a complete constructor would look something like this (formatted for readability):
public Student(int id, int gradeLevel, String name,
String school, String major, double gpa)
{
// fill your fields in here
}
I think you should read through the docs for a constructor again ;)
With Student sam = new Student(12, "Oakton High School", "Biology");
you are creating a Student-object with the given parameters and storing it in the variable sam.
When you call sam = new Student(154324, "Sam Bay", 3.56); you are again creating a new Student-object and storing it in sam. You are not modifying the first object but rather discarding it and creating a new one.
You should try adding a method to your Student object like:
public void setAdditionalValues(int id, String name, double gpa){
this.id = id;
this.name = name;
this.gpa = gpa;
}
Hope this is helpful :)
EDIT: as mentioned earlier you could also use one constructor that takes all the arguments or implement setters for each attribute of the Student-object like this:
public void setName(String name){
this.name = name;
}
I'm trying to get the toString from the class Employee, but all it does is give me an output of [ ]. I got the input for the toString method, but any ideas on how to get it to carry out to the output?
public class A5
{ // begin class
public static void main(String[] args)
{ // begin main
// ********** CREATE OBJECTS **********
ArrayList<Employee> employeeInfo = new ArrayList<Employee>();
// ********** GET INPUT **********
// get the employee's ID
System.out.println("\nEnter your employee ID.");
ID = keyboard.nextInt(); //get the input and set it to the local varaible ID
//System.out.println("Employee ID: " + ID);
// get the employee's hours worked
System.out.println("\nEnter the amount of hours you worked this week.");
Hours = keyboard.nextInt(); //get the input and set it to the local varaible HoursWorked
//System.out.println("Hours worked: " + Hours);
// get the employee's wage
System.out.println("\nEnter your wage.");
Wage = keyboard.nextDouble(); //get the input and set it to the local varaible Wage
//System.out.println("Employee wage: " + Wage);
// ********** OUTPUT **********
System.out.println(employeeInfo.toString());
// ********** CLOSING MESSAGE **********
System.out.println("\nEnd of Processing!");
} // end main
} // end class
And the other class is:
public class Employee
{ // begin class
private int ID; // employee's id
private int Hours; // number of hours worked
private double Wage; // pay per hour
public Employee(int IDnumber)
{
ID = IDnumber;
}
public int getID()
{
return ID;
}
public void setWage(double HourlyWage)
{
Wage = HourlyWage;
}
public double getWage()
{
return Wage;
}
public void setHours(int hoursWorked)
{
Hours = hoursWorked;
}
public double getHours()
{
return Hours;
}
public String toString() // overrides the toString method inherited from object
{ // begin toString
String strout = "\nId \t\t Hours \t\t Rate \t\t Regular Pay \t Overtime Pay \t Gross Pay\n";
strout += ID + "\t " + Hours + "\t\t\t $" + (df1.format(Wage)));
return strout;
} // end toString
} // end class
You are calling the toString method of the ArrayList, not of any Employee. In fact you did not yet create an instance of that class. Try:
System.out.println(new Employee());
EDIT:
First:
OK, well, you need atleast to make some Employee objects and add them to your list ;) Otherwise, there is "nothing" (which prints out to "nothing"). So after you read all your stuff from the user's input (ID and so) make a new Employee out of it:
// make a new employee
Employee employee = new Employee(id); // pass your id
employee.setWage(...); // pass your wage
... // pass other things
// add it to the list of course
employeeInfo.add(employee);
Now there is an employee in the list which you can print. You can test if something is on the list by asking for its size:
System.out.println(employeeInfo.size());
Second:
You don't call toString() on your employee class, which you properly want to print. You call it on your list of employees. Therefor you will see the result of the toString() method of the ArrayList class (which is not what you expect, but what is correct). Instead, iterate over the list and print every employee. Note that the toString() method will be called automatically, since System.out.println will convert your object to a string (which actually means to call this method).
Try this:
for(Employee employee: employeeInfo)
System.out.println(employee);
Your employeeInfo object seems to be empty, and thus you are printing an empty list.
Make sure you put values in it before printing.
Note that the toString() of the ArrayList is implemented to recursively invoke toString() of its object, so it is fine to use ArrayList.toString() to print the entire ArrayList - if that's what you want. No need to iterate for all elements.
You are printing the toString of an Array. employeeInfo is an ArrayList of Employees.
Iterate and print employees like:
for (Employee e : employeeInfo)
{
System.out.println(e.toString());
}
I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling
Hey i have an EmployeeStore which i have used a hashmap for this. The variables that the map stores are email name and id. I have a method called SearchByEmail but there is a problem with this. The method returns false when the user inputs a correct employee email into the UI.
Here is my code:
This is in the MainApp
case 2:
System.out.println("Search by Email.");
Employee employeeSearchEmail = MenuMethods.userInputByEmail();
Store.searchByEmail(employeeSearchEmail.getEmployeeEmail());
MenuMethods
//Imports
import java.util.Scanner;
//********************************************************************
public class MenuMethods
{
private static Scanner keyboard = new Scanner(System.in);
//Methods for the Company Application menu.
//Method for validating the choice.
public static int getMenuChoice(String menuString, int limit, String prompt, String errorMessage)
{
System.out.println(menuString);
int choice = inputAndValidateInt(1, limit, prompt, errorMessage);
return choice;
}
//********************************************************************
//This method is used in the getMenuChoice method.
public static int inputAndValidateInt(int min, int max, String prompt, String errorMessage)
{
int number;
boolean valid;
do {
System.out.print(prompt);
number = keyboard.nextInt();
valid = number <= max && number >= min;
if (!valid) {
System.out.println(errorMessage);
}
} while (!valid);
return number;
}
//********************************************************************
public static Employee userInput()
{
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
System.out.println("Please enter the Employee ID:");
int employeeId = keyboard.nextInt();
temp = keyboard.nextLine();
System.out.println("Please enter the Employee E-mail address:");
String employeeEmail = keyboard.nextLine();
return e = new Employee(employeeName , employeeId, employeeEmail);
}
//********************************************************************
public static Employee userInputByName()
{
//String temp is for some reason needed. If it is not included
//The code will not execute properly.
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Name:");
String employeeName = keyboard.nextLine();
return e = new Employee(employeeName);
}
//********************************************************************
public static Employee userInputByEmail()
{
//String temp is for some reason needed. If it is not included
//The code will not execute properly.
String temp = keyboard.nextLine();
Employee e = null;
System.out.println("Please enter the Employee Email:");
String employeeEmail = keyboard.nextLine();
//This can use the employeeName's constructor because java accepts the parameters instead
//of the name's.
return e = new Employee(employeeEmail);
}
//********************************************************************
}
SearchByEmail
public boolean searchByEmail(String employeeEmail)
{
//(for(Employee e : map.values()) {...})
//and check for each employee if his/her email matches the searched value
boolean employee = map.equals(employeeEmail);
System.out.println(employee);
return employee;
}
First of all,
map.equals(employeeEmail);
doesn't really make sense. map is a Hashmap, and employeeEmail is a String. Under what conditions would they be equal?
It is unclear what you store in the map and how, since you have neither included the declaration of the map, nor the code that inserts new values. I'll assume for now that you store mappings like name -> Employee. If you want to search for an employee based on an email address I suggest you do something like
Employee findByEmail(String email) {
for (Employee employee : yourMap.values())
if (employee.getEmail().equals(email))
return employee;
// Not found.
return null;
}
then to check if an employee with email exists, you could do
public boolean searchByEmail(String employeeEmail) {
boolean employee = findByEmail(employeeEmail) != null;
System.out.println(employee);
return employee;
}
I assume map is of type Map<S,T> for some S,T, and thus it is not of the same type as employeeEmail, and specifically it does not equals() it.
I suspect you are looking for Map.containsValue() (if the email is the value in the map) or Map.containsKey() (if the email is the key of the map), depending on what exactly map is mapping, if the mapping is to/from the string value.
EDIT: based on clarifications on comments:
Since the email is not a key nor value in map, the suggested solution won't work as it is. So you can chose one of those:
Use #aioobe's solution to iterate and check each email.
Add an extra field to the class: Map<String,Employee> map2 which will map: email_address->employee. Given this map, you can search for an email using map2.containsKey(email). It will ensure faster lookup for an employee from an email and the expanse of holding an extra map. I'd go with this choice if I were you.