I'm working on what I thought was a straightforward program to accept user inputs and store them in an ArrayList. I created a separate class containing an object and a constructor (first name, last name, and an integer).
In the main method, I prompt the user for input within a while loop and add a new Document object to the ArrayList on each iteration. When I print the array, the output isn't what I expected. The string elements of the last Document object entered print in every instance of the array, while the integer element of the Document object updates correctly. If anyone could point me in the right direction I would really appreciate the help! I'm stumped!
Main Method:
mport java.util.Scanner;
import java.util.ArrayList;
public class ExceptionDriver
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
ArrayList<Document> someStuff = new ArrayList<Document>();
char quit = 'Y';
String firstname, lastname;
int code;
while (quit == 'Y')
{
System.out.print("\n First Name: ");
firstname = scan.next();
System.out.print(" Last Name: ");
lastname = scan.next();
System.out.print(" Document Code: ");
code = scan.nextInt();
someStuff.add (new Document(lastname, firstname, code));
System.out.print(" Enter Another Record? (Y/N)");
String word = scan.next();
word = word.toUpperCase();
quit= word.charAt(0);
}
for(Document stuff : someStuff)
System.out.println(stuff);
}
}
Constructor
public class Document
{
public static String firstname, lastname;
private int code;
public Document (String Last, String First, int docCode)
{
firstname = First;
lastname = Last;
code = docCode;
}
public String toString ()
{
return "\n\n Name: " + lastname + ", " + firstname + "\n Document Code: " + code + "\n";
}
public boolean equals (Object other)
{
return (lastname.equals(((Document)other).getLast())&&
firstname.equals(((Document)other).getFirst()));
}
public int compareTo (Object other)
{
int result;
String otherFirst = ((Document)other).getFirst();
String otherLast = ((Document)other).getLast();
if (lastname.equals(otherLast))
result = firstname.compareTo(otherFirst);
else
result = lastname.compareTo(otherLast);
return result;
}
public String getFirst ()
{
return firstname;
}
public String getLast ()
{
return lastname;
}
}