So i have 3 classes, and one that runs all the code. A student class, a Graduate student class and an undergraduate class, and a class called lab 4 that runs the code. The code asks for how many grad students and how many undergrad students there are, then asks the user to input all the information for that number of each. After all the info is inputed, the under grad or grad student objects are added to an array list of students. after all the students are added, then prints all the information. However when i input all the information, the array does not print, the program terminates. How do i get the array to print out?
Code:
Lab 4: creates the student objects, array list, adds them to the array, and the prints all information for objects added to the array list
import java.util.ArrayList;
import java.util.Scanner;
public class Lab04 {
public static void main(String[] args) {
ArrayList <Student> studentList = new ArrayList <Student>();
Scanner s = new Scanner(System.in);
System.out.println("How many Graduate Students do you want to store?");
int numOfStudents = s.nextInt();
s.nextLine();
for (int i = 0; i < numOfStudents; i++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's graduate major?");
String gradMajor = s.nextLine();
System.out.println("What is the student's undergraduate major?");
String underMajor = s.nextLine();
System.out.println("What is the student's undergradute school? ");
String underSchool = s.nextLine();
GraduateStudent gradStu = new GraduateStudent(name, GPA, ID, highSchool, gradMajor, underMajor,
underSchool);
studentList.add(gradStu);
}
System.out.println("How many UnderGraduate students are there?");
int numOfUnder = s.nextInt();
s.nextLine();
for (int j = 0; j < numOfUnder; j++) {
System.out.println("What is the student's name?");
String name = s.nextLine();
System.out.println("What is the student's GPA?");
double GPA = s.nextDouble();
s.nextLine();
System.out.println("What is the student's ID?");
String ID = s.nextLine();
System.out.println("What is the student's High School?");
String highSchool = s.nextLine();
System.out.println("What is the student's major?");
String major = s.nextLine();
System.out.println("What the student's minor?");
String minor = s.nextLine();
UnderGraduate UnderGrad = new UnderGraduate(name, GPA, ID, highSchool, major, minor);
studentList.add(UnderGrad);
}
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
}
}
Student Class:
public class Student {
private String name;
private double gpa;
private String id;
private String highSchool;
//private String major;
//private String minor;
public Student() {
name = "";
gpa = 0.0;
id = "";
highSchool = "";
//major = "";
//minor = "";
}
public Student(String name, double gpa, String id, String highSchool){
this.name = name;
this.gpa = gpa;
this.id = id;
this.highSchool = highSchool;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getGpa() {
return gpa;
}
public void setGpa(double gpa) {
this.gpa = gpa;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getHighSchool() {
return highSchool;
}
public void setHighSchool(String highSchool) {
this.highSchool = highSchool;
}
public String getStudentInformation() {
String result = "Name: " + name + " GPA: " + gpa + " ID: " + id
+ " High School: " + highSchool;
return result;
}
}
graduate Class:
public class GraduateStudent extends Student {
private String gradMajor;
private String underMajor;
private String underSchool;
public GraduateStudent(String name, double gpa, String id, String highSchool,
String gradMajor, String underMajor, String underSchool) {
super(name, gpa, id, highSchool);
this.gradMajor = gradMajor;
this.underMajor = underMajor;
this.underSchool = underSchool;
}
public String getGradMajor() {
return gradMajor;
}
public void setGradMajor(String gradMajor) {
this.gradMajor = gradMajor;
}
public String getUnderMajor() {
return underMajor;
}
public void setUnderMajor(String underMajor) {
this.underMajor = underMajor;
}
public String getUnderSchool() {
return underSchool;
}
public void setUnderSchool(String underSchool) {
this.underSchool = underSchool;
}
#Override
public String getStudentInformation() {
String result = super.getStudentInformation()+
"Graduate Major: " + gradMajor + "Undergraduate Major: " + underMajor +
"Undergraduate School: " + underSchool;
return result;
}
}
Because you're not printing anything. Change
for (int j = 0; j < studentList.size(); j++) {
(studentList.get(j)).getStudentInformation();
}
to
for (int j = 0; j < studentList.size(); j++) {
System.out.println((studentList.get(j)).getStudentInformation());
}
When you ask getStudentInformation, it returns a String, what you want to do now is to System.out.println(...) this String object
Related
I created a three-class program. In the third class, I should fill the array with the values "name", "surname", "code", and "age". What happens though is that my array is always "null", and I can't fill it. Thank you all for your help.
First class:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i=0, min=150;
System.out.println("How many teachers do you want to enter information?");
i=in.nextInt();
for(int j=0; j<i; j++)
{
System.out.println("Enter the teacher's name");
name=in.next();
System.out.println("Enter the teacher's surname");
surname=in.next();
System.out.println("Enter the teacher's code");
code=in.nextInt();
System.out.println("Enter the teacher's age");
age=in.nextInt();
Teacher d = new Teacher(name, surname, code, age);
System.out.println(d.getCode());
System.out.println(d.getSurname());
System.out.println(d.getAge());
University c = new University(name, surname, code, age);
min=c.MinimumAge(age, min);
}
System.out.println(min);
}
}
Second class:
public class Teacher
{
protected String name;
protected String surname;
protected int code;
protected int age;
public Teacher(String name, String surname, int code, int age)
{
this.name=name;
this.surname=surname;
this.code=code;
this.age=age;
}
public String getName()
{
return name;
}
public int getCode()
{
return code;
}
public String getSurname()
{
return surname;
}
public int getAge()
{
return age;
}
}
Third class (I put "0" as a location for filling the array just to do tests.):
public class University
{
private Teacher[] array=new Teacher[4];;
public University(String name, String surname, int code, int age)
{
array[0] = new Teacher(name, surname, code, age);
}
public int MinimumAge(int age, int min)
{
if (age<min)
min=age;
return min;
}
}
The class University has not been implemented correctly. You can implement it as:
class University {
private int counter = 0;
private final int MAX = 4;
private Teacher[] array = new Teacher[MAX];
public void addTeacher(Teacher teacher) {
if (counter < MAX) {
array[counter++] = teacher;
}
}
public int minimumAge() {
if (counter == 0) {
return 0;
}
int min = array[0].getAge();
for (int i = 1; i < counter; i++) {
if (array[i].getAge() < min) {
min = array[i].getAge();
}
}
return min;
}
}
Accordingly, you need to change your code in main as shown below:
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name, surname;
int code, age, i = 0, min = 150;
University university = new University();
System.out.print("How many teachers do you want to enter information?: ");
i = in.nextInt();
for (int j = 0; j < i; j++) {
System.out.print("Enter the teacher's name: ");
name = in.next();
System.out.print("Enter the teacher's surname: ");
surname = in.next();
System.out.print("Enter the teacher's code: ");
code = in.nextInt();
System.out.print("Enter the teacher's age: ");
age = in.nextInt();
university.addTeacher(new Teacher(name, surname, code, age));
}
System.out.println(university.minimumAge());
}
}
A sample run:
How many teachers do you want to enter information?: 2
Enter the teacher's name: a
Enter the teacher's surname: b
Enter the teacher's code: 1
Enter the teacher's age: 23
Enter the teacher's name: x
Enter the teacher's surname: y
Enter the teacher's code: 2
Enter the teacher's age: 15
15
I am trying to utilize the toString() in a class I have called Employee(). I have a 1D array of type Employee, which stores Employee Data, which include the Employee ID, Employee Name, Employee Address, and Employee Hire Date. I want the user to specify the amount of employees, and then enter the relevant data for however many employees the user wants. I then want to print the result for the user with the information entered. I keep getting some results that are null. I tried using an If statement that printed output if it didn't equal null, but that didn't work. I know the output works if I print out a single variable, such as address, but I want all variables to print out. Thank you for any help.
public class Address
{
public String address;
public void getAddress(String a)
{
address = a;
}
public String toString()
{
return address;
}
}
public class Name
{
String name;
public void getName(String n)
{
name = n;
}
public String toString()
{
return name;
}
}
public class Date
{
public String date;
public String date1;
public void getDate(int d, int m, int y)
{
date1 = (m + "/" + d + "/" + y);
}
public String toString()
{
return date1;
}
}
import java.util.Scanner;
public class Employee
{
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y)
{
hireDate.getDate(d, m, y);
}
public void getID(int x)
{
number = x;
}
public void setName( String n)
{
name1.getName(n);
}
public void getAddress(String a)
{
address1.address = a;
}
String z;
public String toString()
{
number1 = String.valueOf(number);
String name2 = String.valueOf(name1);
String address2 = String.valueOf(address1);
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
for (int i = 0; i < input1; i++)
{
Employee [] employees = new Employee[4];
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[0] = new Employee();
employees[0].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[1] = new Employee();
employees[1].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[2] = new Employee();
employees[2].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[3] = new Employee();
employees[3].getDate1(input2, input3, input4);
for (int p = 0; p < employees.length; p++)
{
System.out.println(employees[p]);
}
}
}
}
I have create classes which were needed. You can change them but you are creating employee object every time. I have corrected the code debug it and you will know what was wrong.
import java.util.Calendar;
import java.util.Date;
import java.util.Scanner;
class Name {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
class Address {
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class Employee {
private int number;
private Name name1 = new Name();
private Address address1 = new Address();
private Date hireDate = new Date();
String number1;
public void getDate1(int d, int m, int y) {
Calendar calendar = Calendar.getInstance();
calendar.set(y, m, d);
hireDate = calendar.getTime();
}
public void getID(int x) {
number = x;
}
public void setName(String n) {
name1.setName(n);
}
public void getAddress(String a) {
address1.setAddress(a);
}
String z;
public String toString() {
number1 = String.valueOf(number);
String name2 = name1.getName();
String address2 = address1.getAddress();
String hireDate2 = String.valueOf(hireDate);
z = number1 + " " + name2 + " " + address2 + " " + hireDate2;
return z;
}
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter amount of Employees: ");
int input1 = input.nextInt();
input.nextLine();
Employee[] employees = new Employee[input1];
for (int i = 0; i < input1; i++) {
System.out.println("Please enter the employee ID: ");
int employeeID = input.nextInt();
input.nextLine();
employees[i] = new Employee();
employees[i].getID(employeeID);
System.out.println("Please enter the employees Name: ");
String name2 = input.nextLine();
employees[i].setName(name2);
System.out.println("Please enter the employee's address: ");
String address2 = input.nextLine();
employees[i].getAddress(address2);
System.out.println("please enter hire date, day (1-31),");
System.out.print("month (1-12), year (1901 - 2019) in order on seperate");
System.out.print(" lines: ");
int input2 = input.nextInt();
int input3 = input.nextInt();
int input4 = input.nextInt();
employees[i].getDate1(input2, input3, input4);
System.out.println(employees[i]);
}
}
}
import java.util.*;
import java.io.*;
public class Patient
{
private String patientId;
private String patientName;
private String gender;
private int age;
private String patientWardNumber;
private int patientBedNumber;
private String dateRegistered;
private String treatment;
private int wardedDuration;
private double price;
private double payment;
public Patient()
{
String patientId =" ";
String patientName =" ";
String patientWardNumber =" ";
String dateRegistered =" ";
String treatment =" ";
int patienBedDuration = 0;
int wardedDuration = 0;
int age = 0;
String gender = " ";
double price = 0.00;
}
public Patient(String ID,String N,String G,int A,String WN,int BN,String DR,String T,int WD)
{
patientId = ID;
patientName = N;
gender = G;
age = A;
patientWardNumber = WN;
patientBedNumber = BN;
dateRegistered = DR;
treatment = T;
wardedDuration = WD;
}
public void SetPatient(String ID,String N,String G,int A,String WN,int BN,String DR,String T,int WD)
{
patientId = ID;
patientName = N;
gender = G;
age = A;
patientWardNumber = WN;
patientBedNumber = BN;
dateRegistered = DR;
treatment = T;
wardedDuration = WD;
}
public String getPatientId()
{
return patientId;
}
public String getPatientName()
{
return patientName;
}
public String getGender()
{
return gender;
}
public int getAge()
{
return age;
}
public String getPatientWardNumber()
{
return patientWardNumber;
}
public int getPatientBedNumber()
{
return patientBedNumber;
}
public String getDateRegistered()
{
return dateRegistered;
}
public String getTreatment()
{
return treatment;
}
public int getWardedDuration()
{
return wardedDuration;
}
public double getPrice()
{
return price;
}
public double getPayment()
{
return payment;
}
public String toString()
{
return patientId+" "+patientName+" "+gender+" "+age+" "+patientWardNumber+" "+patientBedNumber+" "+dateRegistered+" "+treatment+" "+wardedDuration+" "+price+" "+payment;
}
public static void main(String[]args)
{
ArrayList PatientList = new ArrayList();
Scanner scan = new Scanner(System.in);
System.out.println("Enter how many patient are : ");
int num = scan.nextInt();
for(int i=0; i<num; i++)
{
System.out.println("Enter patient ID: ");
String patientId = scan.next();
System.out.println("Enter patient Name: ");
String patientName = scan.next();
System.out.println("Enter the patient's gender: ");
String gender = scan.next();
System.out.println("Enter the patient's age: ");
int age = scan.nextInt();
System.out.println("Enter patient ward number: ");
String patientWardNumber = scan.next();
System.out.println("Enter patient's Bed Number: ");
int patientBedNumber = scan.nextInt();
System.out.println("Enter patient's registeration date: ");
String dateRegistered = scan.next();
System.out.println("Enter the treatment: ");
String treatment = scan.next();
System.out.println("Enter the ward duration: ");
int wardedDuration = scan.nextInt();
Patient data = new Patient(patientId,patientName,gender,age,patientWardNumber,patientBedNumber,dateRegistered,treatment,wardedDuration);
PatientList.add(data);
}
System.out.println("Total patients are: "+PatientList.size());
System.out.println("Enter patient name : ");
Patient D= null;
Object data ;
String user=scan.next();
boolean found=false;
while(!PatientList.isEmpty())
{
if(D.getPatientName().equalsIgnoreCase(user))
{
found=true;
System.out.println(D.toString());
}
else if (found==false)
{
System.out.println("Patient is not found ! TRY AGAIN");
}
}
}
}
I got 2 problems while running this coding.First i cannot enter value for my ward duration. .Second,when i want to search my patient,it cannot display the information about the patient.Its say null pointer exception.i'm still beginner at java.someone can show me the solution?
This is my output
Because you haven't initialized your Patient object D inside the main() method.
Patient D= null;
and invoking a method on it.
if(D.getPatientName().equalsIgnoreCase(user)){ // Here D is null
found=true;
System.out.println(D.toString());
}
You have to create an object of Patient and initialized variable D like,
Patient D= new Patient();
For your "ward duration" input problem; you are reading strings with Scanner.next(). Note that this only reads one word. So if you were to enter "Level 1" for, e.g., treatment, only "Level" would be read; the "1" would be left on the stream and could corrupt later input (in your case, the "1" is being read by the nextInt() call for ward duration).
I suggest using Scanner.nextLine() for those string inputs instead. That way it will read every word on the full line, and will allow you to enter data that contains spaces without issue.
As for your NullPointerException, Kugathasan Abimaran's answer covers that well.
Also, you have another smaller issue. In your Patient constructor, you are not actually initializing any of the member fields. You are declaring and initializing local variables instead:
public Patient() {
String patientId = " ";
String patientName = " ";
String patientWardNumber = " ";
String dateRegistered = " ";
String treatment = " ";
int patienBedDuration = 0;
int wardedDuration = 0;
int age = 0;
String gender = " ";
double price = 0.00;
}
Should be:
public Patient() {
patientId = " ";
patientName = " ";
patientWardNumber = " ";
dateRegistered = " ";
treatment = " ";
patientBedNumber = 0; // <- note: "patienBedDuration" was probably a typo
wardedDuration = 0;
age = 0;
gender = " ";
price = 0.00;
}
By the way, traditionally "" is used to represent an empty string, not " ". Also, it's redundant to initialize the numeric fields to 0 because that's their default initial value anyways.
My code is not compiling and my biggest issue is that line 32 compiles but 42 does not and the methods they come from are written exactly the same. The error message is error cannot find symbol.
import java.util.*;
import java.text.*;
public class CourseApp{
public static void main(String[] args){
Scanner s = new Scanner (System.in);
DecimalFormat df = new DecimalFormat("$0.00");
int initialSize;
boolean q = true;
System.out.println("Enter how many courses you would like to enter info rmation for? ");
try{initialSize = s.nextInt();}
catch(NumberFormatException sonic){
while(initialSize <= 0){
System.out.println("Please enter an integer greater than 0 (ie5). ");
initialSize = s.nextInt();}}
ArrayList <Course> courseArrayList = new ArrayList<Course> (initialSize);
String number="";
String name="";
String instr="";
String text="";
for (int i = 0; i < initialSize; i++){
courseArrayList.add(new Course(number, name, instr, text));
System.out.println("Enter in course information. ");
do{
courseArrayList.get(i).setNumber("");
System.out.println("Please enter the course number: ");
courseArrayList.get(i).setNumber(s.nextLine());
}while(courseArrayList.get(i).getNumber().equals(""));
do{
courseArrayList.get(i).setName("");
System.out.println("Please enter the course name: ");
courseArrayList.get(i).setName(s.nextLine());
}while(courseArrayList.get(i).getName().equals(""));
do{
courseArrayList.get(i).setLastName("");
System.out.println("Please enter the Instructor's last name: ");
courseArrayList.get(i).setLastName(s.nextLine());
}while(courseArrayList.get(i).getLastName().equals(""));
do{
courseArrayList.get(i).setFirstName("");
System.out.println("Please enter the Instructor's first name: ");
courseArrayList.get(i).setFirstName(s.nextLine());
}while(courseArrayList.get(i).getFirstName().equals(""));
do{
courseArrayList.get(i).setUserName("");
System.out.println("Please enter the Instructor's user name: ");
courseArrayList.get(i).setUserName(s.nextLine());
}while(courseArrayList.get(i).getUserName().equals(""));
String[] instrr = new String[3];
instrr[0]=courseArrayList.get(i).getLastName()+", ";
instrr[1]=courseArrayList.get(i).getFirstName()+"\n";
instrr[2]=courseArrayList.get(i).getUserName()+"#K-State.ksu";
instr = instrr[0]+instrr[1]+instrr[2];
System.out.println("Please enter the required text book's title: ");
courseArrayList.get(i).setTitle(s.nextLine());
System.out.println("Please enter the required text book's author: ");
courseArrayList.get(i).setAuthor(s.nextLine());
System.out.println("Please enter the required text book's price: ");
try{courseArrayList.get(i).setPrice(s.nextDouble());}
catch(NumberFormatException shadow){
while(courseArrayList.get(i).setPrice(s.nextDouble()) < 0){
System.out.println("Please enter a positive numerical value. ");
courseArrayList.get(i).setPrice(s.nextDouble());}}
String[] textt = new String[3];
textt[0]=courseArrayList.get(i).getTitle()+"\n";
textt[1]=courseArrayList.get(i).getAuthor()+"\n";
textt[2]=df.format(courseArrayList.get(i).getPrice())+"\n";
text = textt[0]+textt[1]+textt[2];}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}
System.out.println("Please enter a course number");
String a = s.nextLine();
for (int i = 0; i < initialSize; i++){
if (a.equals(courseArrayList.get(i).getNumber())){
courseArrayList.remove(i);}
else if (! a.equals(courseArrayList.get(initialSize-1).getNumber())){
do {
System.out.println("Course number not found.");
System.out.println("Please enter a valid course number: ");
a = s.nextLine();
for (int j = 0; j < initialSize; j++){
if (a.equals(courseArrayList.get(j).getNumber())){
q=false;
courseArrayList.remove(j);}}
} while (q=true);}
else {}}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}}}
this is from a different class and this part does not compile
public void setLastName(String lname){
lastName=lname;}
the instructor class is:
public class Instructor
{
private String lastName; // Last name
private String firstName; // First name
private String userName; // Username ID
public Instructor(String lname, String fname, String un){
lastName = lname;
firstName = fname;
userName = un;}
public Instructor(Instructor object2){
lastName = object2.lastName;
firstName = object2.firstName;
userName = object2.userName;}
public void setLastName(String lname){
lastName=lname;}
public String getLastName(){
return lastName;}
public void setFirstName(String fname){
firstName=fname;}
public String getFirstName(){
return firstName;}
public void setUserName(String un){
userName=un;}
public String getUserName(){
return userName;}
public String toString()
{
return str;
}
}
this is from a different class and this part does compile
public void setName(String name){
courseName=name;}
the course class is:
public class Course
{
private String courseNumber; // e.g. CIS 200
private String courseName; // e.g. Programming Fundamentals
private Instructor instructor; // Course instructor (object)
private TextBook textBook; // Required Course textbook (object)
public Course(String number, String name, String instr, String text){
courseNumber = number;
courseName = name;
instructor = new Instructor(instr);
textBook = new TextBook(text);}
public String getName(){
return courseName;}
public void setName(String name){
courseName=name;}
public String getNumber(){
return courseNumber;}
public void setNumber(String number){
courseNumber=number;}
public Instructor getInstructor(){return new Instructor(instructor);}
/**getTextBook method
#return A reference to a copy of this course's TextBook object.*/
public TextBook getTextBook(){return new TextBook(textBook);}
/**toString method
#return A string containing the course information.*/
public String toString(){
String str = courseNumber + " " + courseName+ "\n"+
instr+"\n" +
text;
return str;}}
And finally the TextBook class:
import java.text.*;
import java.util.*;
public class TextBook
{
DecimalFormat df = new DecimalFormat("$0.00");
private String title; // Title of the book
private String author; // Author's last name
private double price; // Wholesale cost of the book
public TextBook(String t, String a, double p){
title = t;
author = a;
price = p;}
public TextBook(TextBook object2){
title = object2.title;
author = object2.author;
price = object2.price;}
public void setTitle(String t){
title=t;}
public void setAuthor(String a){
author=a;}
public void setPrice(String p){
price=p;}
public void getTitle(){
return title;}
public void getAuthor(){
return author;}
public void getPrice(){
return price;}
public String toString(){
String str = "Required Textbook: \n" + " " + title+", " + author + ", " + df.format(price);
return str;}}
why does .setLastName() not work but .setName() does
In your class that has this
public void setLastName(String lname){
lastName=lname;
}
Make sure lastName exists as class variable. I am guessing this should be like:
private String lastName;
If you post your Course.java code, we all would be better equipped to explain what might be missing.
I am using the ArrayList Object to create an employee object of type employee...I implement the class and it seems to work, but my problem is that when I insert the employees into the ArrayList it is automatically doesn't insert it. Why is that?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author
*/
import java.util.*;
class Employee {
private String fname;
private String lname;
public Employee (String fname, String lname){
this.fname = fname;
this.lname = lname;
}
public Employee (){
}
public String getLastName(){
return this.lname;
}
public void setLastName(String lname){
this.lname = lname;
}
public String getFirstName(){
return this.fname;
}
public void setFirstName (String fname){
this.fname = fname;
}
public String toString(){
return this.getClass().getName() +" [ "
+ this.fname + " "
+ this.lname + " ]\n ";
}
public Object clone(){ //Object is used as a template
Employee emp;
emp = new Employee(this.fname, this.lname);
return emp;
}
}
//start of main
public class main
{
static Scanner input = new Scanner(System.in);
public static final int MAX_EMPLOYEES = 10;
public static void main(String[] args) {
String fname, lname;
int num;
System.out.print("Enter the number of employees in your system: ");
num = input.nextInt();
ArrayList<Employee> emp = new ArrayList<Employee>(num);
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
for (int x = 1; x < num; x++)
{
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
emp.add(new Employee(fname,lname));
}
num = emp.size();
System.out.println(num);
System.out.println(emp);
}
}
Add:
emp.add(new Employee(fname,lname));
just before your for loop or rewrite your for loop conditional as:
for (int x = 0; x < num; x++)
and get rid of the
System.out.print("Enter the first name: ");
fname = input.next();
System.out.println();
System.out.print("Enter the last name: ");
lname = input.next();
System.out.println();
before the for loop.
Your loop is running 1 less time than is required.
for(int i=0;i<num; i++){
This should fix it.