i am currently using inheritance and as you can see below, i have two classes, the person and the passenger. In the person i have the main toString() method and in the passenger i call a super.toString() and add the new info, priority booking/noOfBags and the ID. The problem i have is, when the user adds a new passenger to the array, when you print the array the data isn't in the same format as entered. I am pretty sure that i have called everything correctly and im not 100% sure why just the name aspect of the toString messes up (notice that the DOB/ID/noOfBags and priority booking all formatted correctly). If anyone can point me as to why just the name is printing incorrectly it would be greatly appreciated.
Code
This is the constructor in the main class Person
public Person()
{
name = new Name();
dateOfBirth = new Date();
}
public Person(String titleIn, String firstNameIn, String surNameIn, int day, int month, int year)
{
name = new Name(titleIn, firstNameIn, surNameIn);
dateOfBirth = new Date(day, month, year);
}
Here is the method i use to get the Name and DOB details of the new passenger
public void read()
{
try
{
Scanner kbInt = new Scanner(System.in);
Scanner kbString = new Scanner(System.in);
System.out.println("***Passenger Details: ***");
System.out.print("Title : ");titleRead=kbInt.nextLine();
System.out.print("First Name : ");FNameRead=kbString.nextLine();
System.out.print("Surname : ");SNameRead=kbString.nextLine();
name = new Name(titleRead, FNameRead, SNameRead);
System.out.println("\n");
System.out.println("***Date of Birth: ***");
System.out.print("Day : ");dayRead=kbInt.nextInt();
System.out.print("Month : ");monthRead=kbInt.nextInt();
System.out.print("Year : ");yearRead=kbString.nextInt();
dateOfBirth = new Date(dayRead, monthRead, yearRead);
}
catch (InputMismatchException e)
{
System.out.print("Incorrect input, please input data in the correct format!");
}
}
And finally for the person class, here is the toString
public String toString()
{
String nameAndAge = "Name = " + name + ", DOB = " + dateOfBirth;
return nameAndAge;
}
In the passenger class which inherits from Person, here is the arraylist being made and the constructor
private ArrayList<Passenger> passengers = new ArrayList<Passenger>();
//Constructor
public Passenger()
{
noOfBags = 0;
priorityBoarding = false;
id = nextid++;
}
//Initiliaze constructor
public Passenger(String titleIn, String firstNameIn, String surnameIn, int day, int month, int year, int bag, boolean pb)
{
super(titleIn, firstNameIn, surnameIn, day, month, year);
noOfBags = bag;
priorityBoarding = pb;
}
Here i add the reading of the noOfBags and priority boarding and add it to the read method in person
public void bagsPriorityRead()
{
Scanner kbInt = new Scanner(System.in);
Scanner kbString = new Scanner(System.in);
super.read();
System.out.print("Number of bags : ");bagsRead=kbString.nextInt();
System.out.print("Priority boarding (Y/N) : ");priorityRead=kbString.next().charAt(0);
}
Finally, here is the toString method in passenger
//ToString Method
public String toString()
{
return " ID: " +id + " - " + super.toString() + " \tNo of Bags: " +bagsRead + "\tDo they have priority boarding? : " +priorityRead;
}
//Added images of the adding in action and the way it is improperly formatted when printing
//Improper formatting when printing
As stated above, if anyone could point to where im going wrong/how to fix my error it would be greatly appreciated. If any more code may be needed to find the source of the problem just let me know.
Thanks in advance,
Jason
Looks like the problem, if anywhere, would be in Name::toString() or that the order of the parameters are wrong in new Name(x, y, z)
String nameAndAge = "Name = " + name + ", DOB = " + dateOfBirth;
But you haven't posted the Name class.
Related
I'm trying to use menu loop than when I finish the first choice an I want to get data in choice 2.
It can't get, this is an error.
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:70)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:248)
at java.base/java.util.Objects.checkIndex(Objects.java:373)
at java.base/java.util.ArrayList.get(ArrayList.java:425)
at craitid_19.main(craitid-19.java:38)
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class craitid_19{
public static void main(String [] args){
while(true){
System.out.println("1 - Insert");
System.out.println("2 - Edit");
System.out.println("3 - View");
System.out.println("4 - Exit");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
infected patient = new infected();
switch (choice){
case 1:
System.out.print("ID = ");
int id = input.nextInt();
System.out.print("name = ");
String name = input.next();
System.out.print("age = ");
String age = input.next();
System.out.print("gender = ");
String gender = input.next();
System.out.print("date = ");
String date = input.next();
System.out.print("province = ");
String province = input.next();
System.out.print("infectby = ");
String infectby = input.next();
patient.children.add(new normal(id, name, age, gender, date, province, infectby));
System.out.print(patient.toString());
continue;
case 2:
System.out.println("Insert ID");
System.out.print(patient.children.get(0));
case 4:
System.out.println("Exiting Program...");
System.exit(0);
break;
default :
System.out.println("This is not a valid Menu Option! Please Select Another");
break;
}
}
}
}
class infected {
public int id;
public String name;
public String age;
public String gender;
public String date;
public String province;
public String infectby;
public String type;
public List<infected> children = new ArrayList<>();
public infected(){
}
#Override
public String toString()
{
String returnString = id + (",") + name + (",") + age + (",") + gender + (",") + date + (",") + province + (",") + infectby + (",") + type + System.lineSeparator();
for (infected child : children)
returnString = child.toString() + System.lineSeparator();
return returnString;
}
}
class normal extends infected{
public normal(int id, String name, String age, String gender, String date, String province, String infectby){
type = "1";
this.id = id;
this.name = name;
this.age = age;
this.gender = gender;
this.date = date;
this.province = province;
this.infectby = infectby;
}
}
Your problem is that you create infected patient inside of while loop. This means you override the data you created every time when you answer the menu. The error actually says that you patient.children List is empty, while you are trying to get the 0 element. So I recommend:
Move initialization of patient object out of while loop (just put it before while).
Check if the list is not empty before you try to read data from it.
Use Java naming convention for classes (they should start from uppercase letter - Infected instead of infected an so on) - this will make your code much more readable.
First you have to replace continue; by break; Then, between line 4 and 5 you have to add this:
infected patient = new infected();
This will call just once the class and the class' constructor, if you want to call the constructor of the class each time the loop repeats you just add
infected patient,
And in the line 13 you replace what you have for:
patient = new infected();
What's the difference between calling the constructor just once or each time the loop repeats?
In the first case, when you add a patient it will remain until you close the program,
In the second case, each time the loop repeats, the patient you added before will be lost.
Choose wisely.
You also should use the Java name convention, the first letter of the classes' name must be uppercase.
I'm learning object-oriented programming in a Java course, and I'm doing a project where a program creates three types of objects: Address, Date, and Employee. The program stores data of several employees and then displays the data in an array of type Employee.
I'm using four different classes: an Address class, a Date class, and an Employee Class, and an EmployeeTest class that creates the array.
Here is the Address class:
public class Address {
private String Street;
private String City;
private String State;
private int ZipCode;
public Address(String St, String Ci, String Sta, int Zip){
Street = St;
City = Ci;
State = Sta;
ZipCode = Zip;
}
public String getEmployeeAddress(){
return (Street + ", " + City + ", " + State + " " + ZipCode);
}
}
The Date Class:
public class Date {
private int Month;
private int Day;
private int Year;
public Date(int M, int D, int Y){
Month = M;
Day = D;
Year = Y;
}
public String getDateString(){
return (Month + "/" + Day + "/" + Year);
}
}
And, the Employee Class:
public class Employee {
private int EmployeeNum;
public void setEmployeeNum(int ENum){
EmployeeNum = ENum;
}
public int getNum(){
return EmployeeNum;
}
public String getDate(){
return Date.getDateString();
}
public String getName(){
return Name.getEmployeeName();
}
public String getAddress(){
return Address.getEmployeeAddress();
}
}
All of these classes are in the same package (I'm using Eclipse). The point of the Employee class is to create an object of type Employee and be able to get it's Address, Name, and HireDate using the Address, Name, and Date classes.
The place where the array comes into play is here:
import java.util.Scanner;
import java.lang.*;
public class EmployeeTest {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("How many employees will have their data stored today?");
int EmployeeAmount = Integer.parseInt(input.nextLine());
Employee [] EmployeeArray = new Employee[EmployeeAmount];
for (int i = 0; i < EmployeeArray.length; i ++){
System.out.print("What is employee " + (i+1) + "'s employee number?");
int EmployeeNumber = Integer.parseInt(input.nextLine());
EmployeeArray[i] = new Employee();
EmployeeArray[i].setEmployeeNum(EmployeeNumber);
System.out.println("What is the first name of employee " + EmployeeNumber + "?");
String EmployeeFirstName = input.nextLine();
System.out.println("What is the last name of employee " + EmployeeNumber + "?");
String EmployeeLastName = input.nextLine();
Name EmployeeName = new Name(EmployeeFirstName, EmployeeLastName);
System.out.println("Please enter the street address: ");
String StreetAddress = input.nextLine();
System.out.println("Please enter the name of the city: ");
String CityName = input.nextLine();
System.out.println("Please enter the two character code for the state: ");
String StateID = input.nextLine();
System.out.println("Please enter this address's zip code: ");
int ZipCode = Integer.parseInt(input.nextLine());
Address EmployeeAddress = new Address(StreetAddress, CityName, StateID, ZipCode);
System.out.println("Finally, what was the month(#) of the hire date?");
int Month = Integer.parseInt(input.nextLine());
System.out.println("What was the day(#)?");
int Day = Integer.parseInt(input.nextLine());
System.out.println("What was the year?");
int Year = Integer.parseInt(input.nextLine());
Date HireDate = new Date(Month, Day, Year);
}
for (int j = 0; j < EmployeeArray.length; j ++){
System.out.println("Employee number: " + EmployeeArray[j].getNum());
System.out.println("Employee Name: " + EmployeeArray[j].getName());
System.out.println("Employee Address: " + EmployeeArray[j].getAddress());
System.out.println("Employee Hiredate: " + EmployeeArray[j].getDate());
}
}
}
The program prompts the user for the number of employees to be stored in the array, then creates an Employee[] of size EmployeeAmount. The idea of the code is that for each Employee in the Array, all of the variables in the other classes are obtained: Employee Number, Employee Name (first and last), Address (Street Address, City, State Code, Zip Code), Hire Date (Month, Day, Year). After all this is obtained, the second for loop iterates through each Employee and displays the info.
The problem I am having is that in the Employeeclass, Eclipse gives me an error in the getDate(), getName(), and getAddress() methods. When I say for example, return Date.getDateString(), Eclipse says that I cannot make a static reference to a non-static method. It's solution is to make getDateString() static, and I tried this, but the problem is that by making all the methods and variables in the Address, Employee, and Date classes, the values are locked. Meaning that the same data will be displayed for all employees.
Here's what I mean. Below is a sample output if I made all the methods and variables static. The text in between the asterisks is what the user inputs.
How many employees will have their data stored today?**2**
What is employee 1's employee number?**1**
What is the first name of employee 1?
**Bob**
What is the last name of employee 1?
**Jones**
Please enter the street address:
**300 1st Avenue**
Please enter the name of the city:
**New York**
Please enter the two character code for the state:
**NY**
Please enter this address's zip code:
**10001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**1**
What was the year?
**2001**
What is employee 2's employee number?**2**
What is the first name of employee 2?
**Bobby**
What is the last name of employee 2?
**Robinson**
Please enter the street address:
**301 1st Avenue**
Please enter the name of the city:
**Los Angeles**
Please enter the two character code for the state:
**CA**
Please enter this address's zip code:
**90001**
Finally, what was the month(#) of the hire date?
**1**
What was the day(#)?
**2**
What was the year?
**2004**
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
Employee number: 2
Employee Name: Bobby Robinson
Employee Address: 301 1st Avenue, Los Angeles, CA 90001
Employee Hiredate: 1/2/2004
By making all of the variables and methods static, the values are locked as shown, which makes the program useless. Does anyone have a solution to this problem? I need a way to display the information of each employee while referencing the methods in the other classes. Now, normally I would just create all the variables and methods under one class called Employee, but the assignment instructions specify that I need to make individual classes.
You are creating a Name, Address, and Date for each iteration of the for loop. But you have not way, nor do you set them on each Employee instance.
You need to add methods to set the values on each Employee and store the information. Something like this:
public class Employee {
private int employeeNum;
private Name name;
private Date hireDate;
private Address address;
public void setEmployeeNum(int eNum){
employeeNum = eNum;
}
public int getEmployeeNum(){
return employeeNum;
}
public void setHireDate(Date date){
this.hireDate = date;
}
public String getHireDate(){
return hireDate.getDateString();
}
public void setName(Name n){
this.name = n;
}
public String getName(){
return name.getEmployeeName();
}
public void setAddress(Address addy){
this.address = addy;
}
public String getAddress(){
return address.getEmployeeAddress();
}
}
Then in your for loop, set the values:
EmployeeArray[i].setName(EmployeeName);
EmployeeArray[i].setAddress(EmployeeAddress);
EmployeeArray[i].setHireDate(HireDate);
By the way, you should not capitalize variables, only classes.
Variables should be camel-cased.
Please excuse what is probably a very basic question, but I am writing a program to store employee info and it works fine until it tries to set the info inside my employee class. It gives a stackoverflow error and I cannot figure out why. Thanks for any help.
Main class:
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner Input = new Scanner(System.in);
System.out.println("Enter the number of employees to enter.");
int employeeCount = Input.nextInt();
Input.nextLine();
Employee employee[] = new Employee[employeeCount];
String namesTemp;
String streetTemp;
String cityTemp;
String stateTemp;
String zipCodeTemp;
String address;
String dateOfHireTemp;
for(int x = 0; x < employeeCount; x++)
{
System.out.println("Please enter the name of Employee " + (x + 1));
namesTemp = Input.nextLine();
System.out.println("Please enter the street for Employee " + (x + 1));
streetTemp = Input.nextLine();
System.out.println("Please enter the city of Employee " + (x + 1));
cityTemp = Input.nextLine();
System.out.println("Please enter the state of Employee " + (x + 1));
stateTemp = Input.nextLine();
System.out.println("Please enter the zip code of Employee " + (x + 1));
zipCodeTemp = Input.nextLine();
address = streetTemp + ", " + cityTemp + ", " + stateTemp + ", " + zipCodeTemp;
System.out.println("Please enter the date of hire for Employee " + (x + 1));
dateOfHireTemp = Input.nextLine();
System.out.println("The employee ID for employee " + (x + 1) + " is " + (x + 1));
employee[x] = new Employee(x, namesTemp, address, dateOfHireTemp);
}
}
}
Employee class:
public class Employee
{
private int employeeID;
private Name name;
private Address address;
private DateOfHire hireDate;
public Employee()
{
}
public Employee(int employeeID, String name, String address, String hireDate)
{
String temp;
Name employeeName = new Name(name);
this.employeeID = employeeID;
}
}
Name class:
public class Name
{
public Name name;
public Name(String name)
{
Name employeeName = new Name(name);
this.name = employeeName;
}
}
The most common cause of StackoverflowExceptions is to unknowingly have recursion, and is that happening here? ...
public Name(String name)
{
Name employeeName = new Name(name); // **** YIKES!! ***
this.name = employeeName;
}
Bingo: recursion!
This constructor will create a new Name object whose constructor will create a new Name object whose constructor will... and thus you will keep creating new Name objects ad infinitum or until stack memory runs out. Solution: don't do this. Assign name to a String:
class Name {
String name; // ***** String field!
public Name(String name)
{
this.name = name; // this.name is a String field
}
Typically a class is used to group data together with functionality. It appears that the Name class is simply a wrapper for a String without adding any functionality. At this point in your Java career, it is probably better to declare String name; in the Employee class and remove the Name class all together. (Note that this would remove the error from your code that Hovercraft Full of Eels described.)
I am getting the error Exception in thread “main” java.lang.NullPointerException?. on my program. What I did was create an array of objects (the array is dbase[], the object is employee). the employee object creates more objects (date, name, and address) that have setter and getter methods. I am getting this error when tryinig to access these object's getter methods when trying to use something such as dbase[0].date.getMonth. I believe this is something wrong with creating the array. I have not included the date or address classes in the interest of saving space, because are basically the same as the name class. thanks for the help.
edit: The error occurred at the second line of the printing block in the main method in the for loop. It occurs at dbase[j].name.getFirst() at line 28
public class test {
public static void main (String[] args) {
int i = Input.getInt ("How many employees would you like to enter? ");
int j;
Employee [] dbase = new Employee [i];
for (j = 0; j < i; j++) {
dbase[j] = new Employee();
}
for (j = 0; j < i; j++) {
String firstName = Input.getString ("What is an employee " + (j + 1) + "'s first name?");
String lastName = Input.getString ("What is this employee's last name?");
String street = Input.getString ("On what street does this employee live?");
String city = Input.getString ("In which city does this employee live?");
String state = Input.getString ("In which state does this employee live? (abbreviation)");
String zipcode = Input.getString ("What is this employee's zip code?");
int month = Input.getInt ("In what month was this employee born? (numeric - January = 1 )");
int day = Input.getInt ("On what day was this employee born?");
int year = Input.getInt ("In what year was this employee born?");
int employeeID = Input.getInt ("What should this employee's employee id be?");
dbase[j] = new Employee(firstName, lastName, street, city, state, zipcode, month, day, year, employeeID);
}
for (j = 0; j < i; j++) {
System.out.print ( "Employee number " + (j + 1) + " is named ");
System.out.print ( dbase[j].name.getFirst() + " " + dbase[j].name.getLast() + " and lives on " + dbase[j].address.getStreet());
System.out.print ( " in " + dbase[j].address.getCity() + " " + dbase[j].address.getState() + ", " + dbase[j].address.getZipcode());
System.out.print ( ". He will be hired on " + dbase[j].date.getMonth() + "-" + dbase[j].date.getDay() + "-" + dbase[j].date.getYear() );
System.out.print ( " and his ID is " + dbase[j].getEmployeeID());
System.out.println ();
}
}
}
class Employee {
int employeeID = 0;
name name;
address address;
date date;
Employee(){
}
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name name = new name( firstName1, lastName1 );
address address = new address( street1, city1, state1, zipcode1 );
date date = new date( month1, day1, year1);
employeeID = employeeID1;
}
int getEmployeeID() {
return employeeID;
}
}
class name {
String firstName = " ";
String lastName = " ";
name(String newFirstName, String newLastName) {
firstName = newFirstName;
lastName = newLastName;
}
String getFirst() {
return firstName;
}
String getLast() {
return lastName;
}
}
In your constructor for Employee, you're assigning to local variables, not to the fields of the same name.
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name name = new name( firstName1, lastName1 );
address address = new address( street1, city1, state1, zipcode1 );
date date = new date( month1, day1, year1);
employeeID = employeeID1;
}
You can eliminate this problem by removing the type names from the assignment statements:
Employee( String firstName1, String lastName1, String street1, String city1, String state1, String zipcode1, int month1, int day1, int year1, int employeeID1 ) {
name = new name( firstName1, lastName1 );
address = new address( street1, city1, state1, zipcode1 );
date = new date( month1, day1, year1);
employeeID = employeeID1;
}
In addition, you should consider beginning all your type names with an uppercase character. This is almost universal Java style, and helps you identify them at a glance.
class Name { ... }
class Date { ... }
class Address { ... }
One way to reduce the likelihood of name collisions between member and local variables is to adopt a different naming scheme for the former. This is not generally accepted Java style, and some feel antipathy toward it as an incursion of a style that originated in C++. However, it can reduce risk.
class Employee {
int m_employeeID = 0;
Name m_name;
Address m_address;
Date m_date;
...
}
When you have a variable holding an object in Java, this variable is a reference to the object. That means that multiple variables can point to the same object and also that they might point to no object at all. That's null.
When you access something that belongs to an object, either a method or a field, you are dereferencing. However if the variable points to no object (that's null) you get a nullpointer exception.
In your case that could be dbase[j].name or one of the others in the last for-body. And there are two dereferenciations going on: first dbase[j] (I don't see a problem there; actually you are creating multiple objects, i.e. your first for-loop is not needed), or the value of name within your object is not set. Either because Input.getString returned null (we cannot say what that is, because that info is missing from your post) or you didn't set the value in the Employer constructor, which is the case here.
Within the constructor you create local variables.
name name = new name( firstName1, lastName1 );
Instead of
this.name = new name( firstName1, lastName1 );
As a general tip you should look into debuggers (like the one in eclipse or netbeans or whichever ide you use). They can really help you with this kind of problems.
I am writing a program that will read a file and extract the data for each student. I did this successfully with a while loop and input.next(). However, I need to pass the variables into a collection to record each students data, so for each loop I want to add the 4 variables (id, first, last, year) to the collection again. I should note that the collection has to be in a different class and that I will have to be able to search through this collection to find, for example, all students graduating this year.
If anyone could point me in the right direct in regard to storing the variables in a collection, which is in a different class, for each loop.
I know this is a basic question but I am very new to Java so I appreciate everyone’s help!
The first class is
import java.util.*;
import java.io.*;
import java.lang.*;
public class ProcessRecords {
public static void AskUser()
throws Exception {
Scanner preference = new Scanner(System.in);
//Creating a new scanner will allow us to gather user input
boolean flag=true;
//I will use this for my while loop
while (flag) {
System.out.println("What type of Search would you like to run?\n 1)Search for all students\n 2) Search for students graduating in a specific year\n 3)Search for students whose last name begins with a certain string\n");
int searchType=preference.nextInt();
//This variable will store what type of query the user would like to run
switch(searchType) {
case 1:
System.out.println("Gathering Records for all students\n");
//Call Query Method in the Query Class to return all students in the colletion
case 2
System.out.println("What graduation year would you like to search for? \n");
String yearsearch=preference.next();
//Call Query Method to return students who are graduating in the specified year
//Pass the "yearsearch" variable to the Query class to run the search
case 3:
System.out.println("What string would you like to search for? \n");
String lstsearch=preference.next();
//Call Query Method in the Query Class to return students who have the string in their last name
//I need to pass the "lstsearch" variable to the Query class to search through last names
}
}
}
public static void main(String[] args)
throws Exception
{
Scanner input = new Scanner(new File("students.txt"));
//This will import the file
input.nextLine();
//This will skip the headers in the file
System.out.println("Processing file now...");
//Let the user know that the file is being processed
int id;
String last;
String first;
int year;
int i=1;
// Declare variables that we will extract from the file
//Now we will being processing the file with a while loop
List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
while(input.hasNext())
{
id=input.nextInt();
last=input.next();
first=input.next();
year=input.nextInt();
StudentRecord record = new StudentRecord(id, last, first, year);
studentRecords.add(record);
System.out.println(id + " " + last + " " + first + " " + year + "\n");
}
System.out.println(" You have successfully read and printed from the file!");
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
}
}
The next Class is
public class StudentRecord{
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int d, String lt, String ft, int yr){
id=d;
last=lt;
first=ft;
year=yr;
}
public String toString()
{
return id + " " + last + " " + first + " " + year;
}
}
Thanks!
Change the second class:
public class StudentRecord
{
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int d, String lt, String ft, int yr)
{
id=d;
last=lt;
first=ft;
year=yr;
}
public string toString()
{
return id + " " + last + " " + first + " " + year;
}
}
The method is called constructor and you can create instances of this class using it.
In your second class, while running through the loop, you can create new StudentRecord object with actual values for each entry by passing parameters to the constructor:
List<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
while(input.hasNext())
{
id=input.nextInt();
last=input.next();
first=input.next();
year=input.nextInt();
StudentRecord record = new StudentRecord(id, last, first, year);
studentRecords.Add(record);
System.out.println(id + " " + last + " " + first + " " + year + "\n");
}
The ArrayList will serve you as a storage of all StudentRecord objects.
If you override the toString method of your StudentRecord object (as I did above), you can print all student records to the console in a loop:
for (StudentRecord s : studentRecords)
System.out.println(s.toString());
Is there anything wrong with making an ArrayList of StudentRecord objects?
public class StudentRecord {
public int id;
public String last;
public String first;
public int year;
public StudentRecord(int id, String last, String first, int year) {
this.id = id;
this.last = last;
this.first = first;
this.year = year;
}
}
Then right after you grab the values from a file:
ArrayList<StudentRecord> studentRecords = new ArrayList<StudentRecord>();
//...
id = input.nextInt();
last = input.next();
first = input.next();
year = input.nextInt();
studentRecords.add(new StudentRecord(id, last, first, year));
//...