the psuedo for what im trying to do is
-send Array of EMPLOYEE objects to Restaurant Class
-In Class RESTAURANT give each of the employee objects a name and last name (last name not in employee Class but in PERSON Class which Employee CLass Extends.
-print say employeeList[1].getLastName()
hopefully my code explains better
class Person {
public Person(final String last) {
}
}
class Employee extends Person {
private String firstName;
// getFirstName method
// getLastName Method
Employee(final String first, final String last) {
super(last);
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1]; // my array of Employee objects, all set to null
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
}
}
from main when i try to print System.out.printf("first is %d\n",arrayList.getFirst()); i get null for the value as well as the value for the last name so what is the correct way to go about and set values to objects in the array?
Edit arrayList initialized in Class restaurant by
public Table[] create_table_array(Table table,int number) {
Table[] TableList = new Table[number];
int i = 0;
for(i = 0; i < number; i++) {
TableList[i] = table;
}
return TableList;
Your constructor doesn't save firstName, it should look like:
Employee(String first, String last) {
super(last);
firstName = first;
}
You did not make good constructor of Person class and it class does not have instance variable lastName in which you should assign value you get in constructor as a parameter.
Also constructor of Employee does not assign any value to firstName.
What ArrayList ?As i see you are working with arrays?I didn't see it in code anywhere?
System.out.printf("first is %d\n",**arrayList**.getFirst());so command is wrong.
Any code that has meaning to me and can be compilled is to fix those things and delete formatting options you putted in System.out.printf because you are not formatting numbers.
So code look like :
class Person {
String lastName;
public Person(final String last) {
lastName=last;
}
}
class Employee extends Person {
private String firstName;
public String getFirstName()
{return firstName;}
public String getLastName()
{return lastName;}
Employee(final String first, final String last) {
super(last);
firstName=first;
}
}
class Restaurant { // set first object in array have first and last name
public void setFirstLast(final Employee[] employeeList) {
String firstName = "Jovana";
String lastName = "Valdez";
employeeList[0] = new Employee(firstName, lastName); // set up via constructor
}
}
public class Main {
private String lastName;
public static void main(final String[] args) {
Employee[] employeeList = new Employee[1];
Restaurant restaurant = new Restaurant();
restaurant.setFirstLast(employeeList);
System.out.printf("first is "+employeeList[0].getFirstName()+" "+employeeList[0].getLastName());
}
}
Related
I have 3 classes, Session, Employee, and Employees. The Employee class has the constructors and getters, the Employees class has the ArrayList, and I'm trying to add to that ArrayList within the Session class.
public class Employee {
public Employee(String name, String email){
this.name = name;
this.email = email;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
}
public class Employees {
private ArrayList<Employee> employees = new ArrayList<Employee>();
public Employees(){
employees.add(new Employee("John Smith", "johnsmith#email.com"));
}
public void addEmpNew (Employee empNew){
employees.add(empNew);
}
}
public class Session {
private void addEmployee(){
System.out.print("Name: ");
String addEmpName = In.nextLine();
System.out.print("Email: ");
String addEmpEmail = In.nextLine();
Employees v1 = new Employees();
v1.addEmpNew(new Employee(addEmpName, addEmpEmail));
}
}
But when I run it and put in the new employee and use a viewEmployees() method that shows all employees, It doesn't show the new one I added in, only showing the john smith one I pre-wrote in. I have a suspicion there may be something wrong with the addEmpNew method but I'm not sure.
You are creating an instance of Employees (called v1) within the addEmployee method. After the addEmployee method completes, all of the variables inside the method are gone (ready to be garbage collected).
If you are expecting to only have one instance of the Employees, consider making it a global variable.
public class Session {
private final Employees v1 = new Employees();
private void addEmployee(){
System.out.print("Name: ");
String addEmpName = In.nextLine();
System.out.print("Email: ");
String addEmpEmail = In.nextLine();
v1.addEmpNew(new Employee(addEmpName, addEmpEmail));
}
private void printEmployees(){
// you will have to implement the toString method in Employees class
System.out.print("Employees: " + v1.toString());
}
}
import java.util.Arrays;
import java.util.Scanner;
public class employee{
public String name;
public class employee_address{
String street_name;
String city;
String zipcode;
String state;
String country;
}
public static void main(String []args){
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt();
employee[] employees_list = new employee[no_of_employees];
for(int i = 0;i < no_of_employees;i++){
employees_list[i].name = user_input.nextLine();
employees_list[I].employee_address = // this is it ?
}
}
}
In the code above I do understand that the employee_address is a class and can't be accessed
directly without an instance being created like in the code, that makes no sense. but how can I create an instance of the employee_address class that is associate with each employee.
like in the code above 'employee_address' is associated with every employee but how can the class 'employee_address' be initialised and how can I set the street_name, city and the rest of the members in the address class. any ideas would be appreciated.
You can't directly create an instance of inner class, the reason because since it is the property of another instance we always need to use it though the instance of parent variable.
Let's say you have a class, which have two propeties:
public class Employee {
public String name;
public EmployeeAddress emAddress;
}
to access emAddress you need to use through the instance of Employee class, for example -
Employee object = new Employee();
EmployeeAddress empAdd = object.new EmployeeAddress();
Full code:
public class Employee {
public String name;
public EmployeeAddress emAddress;
public class EmployeeAddress {
String street_name;
String city;
String zipcode;
String state;
String country;
public String getStreet_name() {
return street_name;
}
public void setStreet_name(String street_name) {
this.street_name = street_name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipcode() {
return zipcode;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Override
public String toString() {
return "EmployeeAddress [street_name=" + street_name + ", city=" + city + ", zipcode=" + zipcode
+ ", state=" + state + ", country=" + country + "]";
}
}
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int no_of_employees = user_input.nextInt(); // let's say no_of_employees = 1
Employee[] employees = new Employee[no_of_employees];
for (int i = 0; i < no_of_employees; i++) {
Employee object = new Employee();
object.setName("Virat Kohli");
EmployeeAddress empAdd = object.new EmployeeAddress();
empAdd.setCity("New Delhi");
empAdd.setCountry("India");
empAdd.setState("Delhi");
empAdd.setStreet_name("Chandni Chalk");
empAdd.setZipcode("741124");
object.setEmAddress(emAddress);
employees[i] = object;
}
System.out.println(employees[0]);
user_input.close();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public EmployeeAddress getEmAddress() {
return emAddress;
}
#Override
public String toString() {
return "Employee [name=" + name + ", emAddress=" + emAddress + "]";
}
public void setEmAddress(EmployeeAddress emAddress) {
this.emAddress = emAddress;
}
}
I have modified your code to sonar standard.
Below code uses Java naming conventions (which your code does not).
Notes after the code.
import java.util.Scanner;
public class Employee {
private String name;
private EmployeeAddress address;
public class EmployeeAddress {
String streetName;
String city;
String zipcode;
String state;
String country;
}
public static void main(String[] args) {
Scanner userInput = new Scanner(System.in);
int noOfEmployees = userInput.nextInt();
Employee[] employeesList = new Employee[noOfEmployees];
for (int i = 0; i < noOfEmployees; i++) {
employeesList[i] = new Employee();
employeesList[i].name = userInput.nextLine();
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
employeesList[i].address = employeeAddress;
employeesList[i].address.streetName = userInput.nextLine();
}
}
}
An inner class is a normal class. It is not a member of its enclosing class. If you want class Employee to have an [employee] address, as well as a [employee] name, you need to add another member variable to class Employee whose type is EmployeeAdress.
Employee[] employeesList = new Employee[noOfEmployees];
The above line creates an array but every element in the array is null. Hence you need to first create a Employee object and assign it to an element of the array. Hence the following line in my code, above:
employeesList[i] = new Employee();
Since EmployeeAddress is not a static class, in order to create a new instance, you first need an instance of the enclosing class, i.e. Employee. Hence the following line in the above code.
EmployeeAddress employeeAddress = employeesList[i].new EmployeeAddress();
Since all your code is in class Employee, in method main you can directly access the members of both class Employee and EmployeeAddress. Nonetheless you need to be aware of the different access modifiers in java.
A few hints:
stick to naming conventions: class names in Java start with capital letters
use (class) definitions before using them (collect them at the top if not inconventient)
if you are sure you want to use inner classes, set them static, unless you want them to be entangled in generics.
Usually normal classes in each their own file are a lot more flexible and far easier to use
if you use objects that only carry public data, try to use final keyword and initialize them ASAP
use proper objects first, and after finishing them assign them to arrays. avan better would be the use of ArrayList and the like
if Employee contains EmployeeAddress, it should initialize it if conventient. so an object is always responsible for its own stuff
Use try/resrouce/catch
scanner.nextInt() can be problematic with newline/line breaks. For user input better readLine() and parse input
Code:
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Scanner;
public class Employee {
static public class EmployeeAddress {
public final String street_name;
public final String city;
public final String zipcode;
public final String state;
public final String country;
public EmployeeAddress(final Scanner pScanner, final PrintStream pOutPS) {
street_name = readLine(pScanner, pOutPS, "Please enter Street Name:");
city = readLine(pScanner, pOutPS, "Please enter City Name:");
zipcode = readLine(pScanner, pOutPS, "Please enter Zip Code:");
state = readLine(pScanner, pOutPS, "Please enter State:");
country = readLine(pScanner, pOutPS, "Please enter Country:");
}
}
static public String readLine(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
pOutPS.print(pPrompt);
final String value = pScanner.nextLine();
pOutPS.println();
return value;
}
static public int readInt(final Scanner pScanner, final PrintStream pOutPS, final String pPrompt) {
return Integer.parseInt(readLine(pScanner, pOutPS, pPrompt));
}
public final String name;
public final EmployeeAddress address;
public Employee(final Scanner pScanner, final PrintStream pOutPS) {
name = readLine(pScanner, pOutPS, "Please enter Employee Name: ");
System.out.println("Name: " + name);
address = new EmployeeAddress(pScanner, pOutPS);
}
public static void main(final String[] args) {
try (final Scanner user_input = new Scanner(System.in);
final PrintStream output = System.out;) {
final int no_of_employees = readInt(user_input, output, "Please enter number of users: ");
final Employee[] employees_list = new Employee[no_of_employees]; // either this line
final ArrayList<Employee> employees = new ArrayList<>(); // or this line
for (int i = 0; i < no_of_employees; i++) {
output.println("Creating user #" + (i + 1) + "...");
final Employee newEmployeeWithAddress = new Employee(user_input, output);
employees_list[i] = newEmployeeWithAddress; // either this line
employees.add(newEmployeeWithAddress); // or this line
}
}
}
}
I'm new to Java and I've been assigned a Lab to do for school. The Lab requires you to create a class with a set of instance variables with constuctors, getters, and setters. In the next class, its asks you to output variables for these variables, however, it outputs as null.
Class with getters and setters
public class ASEmployee {
//initializes the instance variable firstname of type String
private String firstname;
//initializes the instance variable last name of type string
private String lastname;
//initializes the instance variable monthlySalary of type double
private double monthlySalary;
//makes a constructor for all three instance variables
public ASEmployee (String userFirstname, String userLastname,
double userMonthlySalary) {
setFirstname(userFirstname);
setLastname(userLastname);
setMonthlySalary(userMonthlySalary);
}
//initializes a getter for firstname
public String getFirstname() {
return firstname;
}
//initializes a setter for firstname
public void setFirstname (String userFirstname) {
userFirstname = firstname;
}
//initializes a getter for lastname
public String getLastname(){
return lastname;
}
//initializes a setter for lastname
public void setLastname (String userLastname) {
userLastname = lastname;
}
//initializes a getter for monthlySalary
public double getMonthlySalary() {
return monthlySalary;
}
//initializes a setter for monthlySalary
public void setMonthlySalary (double userMonthlySalary) {
if (monthlySalary >= 0.0) {
userMonthlySalary = monthlySalary;
}
}
}
Class with the thing I'm trying to output`
public class ASPayroll {
public static void main(String[] args) {
//creates an object for the first employee
ASEmployee employee1 = new ASEmployee ("Bob", "Jones", 2000.00);
//creates an object for the second employee
ASEmployee employee2 = new ASEmployee ("Abeba", "Tefera", 3000.00);
//displays the monthly salary of the first employee
System.out.printf("%s %s %s", employee1.getFirstname(), employee1.getLastname()
, employee1.getMonthlySalary());
//displays the monthly salary of the second employee
System.out.printf("%n%s %s %s", employee2.getFirstname(), employee2.getLastname(),
employee2.getMonthlySalary());
And this outputs the strings as "null" and the doubles as "0.0"
Your setters are wrong:
// userLastname is the parameter you are passing in. lastname is the class
// variable. You are setting the parameter to the value of the uninitialized
// value of lastname. userLastname then is thrown away the setter function ends.
userLastname = lastname;
should be:
// Sets your class variable to the value of the parameter being passed in.
lastname = userLastname;
You also have this wrong for firstname and monthlySalary.
Yes it should return null, since you have not assigned it properly
Your setter method for firstName
//initializes a setter for firstname
public void setFirstname (String **userFirstname**) {
**userFirstname** = firstname;
}
It should be like this
//initializes a setter for firstname
public void setFirstname (String userFirstname) {
this.firstname = userFirstname;
}
//initializes a setter for lastname
public void setLastname (String userLastname) {
this.lastname = userLastname;
}
//initializes a setter for monthlySalary
public void setMonthlySalary (double userMonthlySalary) {
if (monthlySalary >= 0.0) {
this.monthlySalary = userMonthlySalary;
}
}
Moreover you dont need the %s in your printf, since here we know what type of data is returned.
Why use printf("%s") for arguments passed to generic methods?
You are confusing yourself in assigning values.
you should write as:
lastname = userLastname;
firstname=userFirstname
This will work out
I am newbie in java and I have a method that accepts 3 parameters, query the db and returns result in an arraylist form (like this [1, Java, 3, Bangalore, 10] ). How can i extract individual element so that I can assign each to a var like int id=1;String name=Java.
Below is the method that
ArrayList searchResult =jSearch.doJobSearch(techName, exp, city);
Iterator searchResultIterator = searchResult.iterator();
PrintWriter out = response.getWriter();
String arrayList[] = new String[searchResult.size()];
if(searchResultIterator.hasNext()){
for(int i =0; i<searchResult.size(); i++){
//searchResult.get(i)
out.println(searchResult.get(i));
}
}else{
out.println("No Job found in selected city");
}
ArrayList works in the sense of [index, element].
By using the get method, you're using index as the parameter and it returns the element at that position. So if you're accessing the element by it's index you already have both the id and element, but a different collection interface might suit you better like a map.
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
Create POJO (Plain Old Java Object). I am providing example how to array list is used when store Real time Object.
package com.appkart.examples;
public class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And Add Employee into Array list and get values
package com.appkart.examples;
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<Employee>();
Employee arun = new Employee(10, "Arun");
Employee ankit = new Employee(20, "Ankit");
Employee jon = new Employee(30, "Jon");
Employee anil = new Employee(40, "Anil");
employees.add(arun);
employees.add(ankit);
employees.add(jon);
employees.add(anil);
for (Employee employee : employees) {
int id = employee.getId();
String name = employee.getName();
System.out.println("id : "+id +" name : "+name);
}
}
}
public class StudentTest{
public static void main(String args[]){
UnderGrad uG1 = new UnderGrad();
uG1.setName("John");
uG1.setMatric("0192345");
System.out.println("Undergarduate Student Info");
uG1.setCourse(new Course("CS1103",3));
uG1.setCourse(new Course("IT4504",3));
uG1.displayStudentInfo();
System.out.println(" ");
PostGrad pG1 = new PostGrad();
pG1.setName("Sam");
pG1.setMatric("G015466");
pG1.setResearch("Empirical Software Engineering");
pG1.setResearch("Data Mining");
System.out.println("Postgrad Student Info");
pG1.displayStudentInfo();
}
}
public class Course{
private String courseName;
private int crhour;
public Course(String n, int c){
courseName = n;
crhour = c;
}
public void setCourseName(String course){
courseName = course;
}
public String getCourseName(){
return courseName;
}
public void setCreditH(int c){
crhour = c;
}
}
public class Student{
private String matric ="-matric required-";
private String name="-name required-";
public Student(){
}
public void setName(String n){
if (n.matches("[a-zA-Z]+") == false)
System.out.println("Invalid Name");
else
name = n;
}
public String getName(){
return name;}
public void setMatric(String m){
matric = m;}
public String getMatric(){
return matric;}
}
public class UnderGrad extends Student{
private Course courseList[];
private int index = 0;
public UnderGrad(){
Course courseList[] =new Course[7];}
public void setCourse(Course courseName){
//Course courseList[]= new Course[2];
}
public Course[] getCourse(){
return courseList;}
public void displayStudentInfo(){
System.out.println("Name: "+getName());
System.out.println("Matric: "+getMatric());
System.out.println("Course List: "+getCourse());
}}
public class PostGrad extends Student{
private String researchArea[];
private int index = 0;
public PostGrad()
{
researchArea = new String[5];
}
public void setResearch(String research){
for(index=0;index<2;index++){
researchArea[index]=research;}
}
public String[] getResearch(){
return researchArea;}
public void displayStudentInfo(){
System.out.println("Name: "+getName());
System.out.println("Matric: "+getMatric());
System.out.println("Research List: "+getResearch());
}}
Output:
Undergarduate Student Info
Name: John
Matric: 0192345
Course List: null
Postgrad Student Info
Name: Sam
Matric: G015466
Course List: [Ljava.lang.String;#2ac9fefa
The problem I cant get the value of String of the course an the research. What should I do?Should I use super reference?
Here:
System.out.println("Course List: "+getCourse());
You're printing out the default toString() returned by an array of String. Don't do that. Iterate through the array and print each item or else use java.util.Arrays.toString(...).
System.out.println("Course List: "+ java.util.Arrays.toString(getCourse()));
You will also need to give your Course class a valid toString() method, one that returns the courseName and perhaps the credit hours. Also I would change the course field to courses or courseList to reflect that it does not represent one single course but rather a collection of courses. Likewise the getter method should reflect the field name change.