View Full Version : arraylists help in java
mdnealy
12-06-2009, 05:33 AM
As you will be able to tell, i am very new at this java coding..I really need help with looping over a database. I have a main and a class. I have to store names then print them. I used arraylists. could you please look and tell me what you think. I believe i am adding the names to the arraylist but when i print it out i only get the last Name entered...hope you all can help.
import java.util.Scanner;
public class Persons {
//private static String firstName;
private static String lastName;
private static Integer yearBorn;
private static Integer selection;
private static String fullName;
//private static String title;
public Persons( String first, String last,Integer year){
setFirstName(first);
setLastName(last);
setYearBorn(year);
}
static Scanner input = new Scanner(System.in);
private static String firstName;
public static void getMainTitle() {
System.out.println("MAIN MENU\nWelcome to the Person Database\n");
}
public static void getMainMenu(){
System.out.println("Main Menu\n1. Add a new Person to the database.\n2. Print the database.\n3. Search for a person in the database.\n4. Exit the application.");
}
// public void setSelection(Integer selection) {
// Persons.selection = selection;
// }
public static int getSelection(){
System.out.println("Please enter selection:");
selection =input.nextInt();
return selection;
}
public void setFirstName( String firstName) {
Persons.firstName = firstName;
}
public static <first>String getFirstName() {
System.out.println("Please enter first name");
firstName= input.next();
return firstName;
}
public void setLastName(String lastName) {
Persons.lastName = lastName;
}
public static <last> String getLastName() {
System.out.println("Please enter last name");
lastName=input.next();
return lastName;
}
public void setYearBorn(Integer yearBorn) {
Persons.yearBorn = yearBorn;
}
public static<year> Integer getYearBorn() {
System.out.println("Please enter year born");
yearBorn=input.nextInt();
return yearBorn;
}
public static String getFullName(){
String fullName = lastName+ firstName+ yearBorn;
return fullName;
}
public static void getDisplayPersons(){
System.out.println("Last Name First Name Age ");
System.out.println("===================== ===================== ===");
}
}
import java.util.ArrayList;
public class PersonsTest {
public static void main(String[] args ){
ArrayList<String> first=new ArrayList<String>();
ArrayList<String> last=new ArrayList<String>();
ArrayList<Integer> year=new ArrayList<Integer>();
Persons.getMainTitle();
Persons.getMainMenu();
Persons.getSelection();
int selection ;
for(selection=0; selection <= 2; selection++)
{
switch(selection){
case 1: do{
first.add(Persons.getFirstName());
for( int i= 0; i < last.size(); i++);
last.add(Persons.getLastName());
for ( int j = 0; j< first.size(); j++);
year.add(Persons.getYearBorn());
for(int k = 0;k<year.size();k++);
Persons.getMainMenu();} while(Persons.getSelection()==1);
case 2: Persons.getDisplayPersons();
do {
System.out.printf("%s\n", Persons.getFullName());}
while ( Persons.getSelection()==2);
}
}
}
}
Fou-Lu
12-06-2009, 03:09 PM
I don't like it. I know, thats brash, but the approach is a little off. Think of Person as nothing more than an object, it can have properties and methods. But its not a collection of Persons, and you should limit any input handling to a main class to prevent environment lockdown (this will let persons work easily on a cli environment, but will prove tricky to implement in a gui environment). So, the only thing that Person should care about is being able to get and set its data. All members should be non-static, since firstname, lastname and year born are all associated with a single instance of a Person, not every person.
interface IPerson
{
public String getFirstName();
public String getLastName();
public int getYearBorn();
public void setFirstName(String sFirstName);
public void setLastName(String sLastName);
public void setYearBorn(int iYearBorn);
}
Then, let you're PersonsTest class take care of all the input for it.
import java.util.ArrayList;
public class PersonsTest
{
public static void main(String[] args)
{
ArrayList<IPerson> ipArr = new ArrayList<IPerson>();
ipArr.add(new Person("Fou", "Lu", 1982));
ipArr.add(new Person("Mdn", "ely", 1990));
for (IPerson p: ipArr)
{
System.out.println("Person: " + p);
}
}
}
I haven't added any input scanning, but it should be a part of you're main application code. So somewhere in you're main method of PersonsTest, you can include ways to prompt for user input. This approach will keep you're Person class generic and allow cli, gui or even file and database approaches possible.
Does that all make sense? Moving into OOP is particularly difficult if you moved out of a procedural language. I personally found Java was a little difficult to absorb at first since I had moved into it from perl and php worlds. Now I make everything in OO when available; so much so that I actually struggle with the procedural approaches I used to use o.O
mdnealy
12-06-2009, 03:37 PM
I will play with that later but we have not done inteface. Java is alot more difficult for some reason the c# and vb..with vb being the easiest. I have three arraylists in my code because I was told i couldn't mix the two strings and an integer. Everytime i think i have it right it fails...this database is completely user interface in our homework. I just don't know if my code is showing it correctly to store(which i only get the last name added so i guess it is wrong). and I need to print over it...anyway to fix the code I do have without going past what we have learned so far? We are only up to collections which i haven't even practiced with the generic..any additional help is appreciated..
Fou-Lu
12-06-2009, 07:34 PM
The interface was just to show you what you're person should have, you can just create a person with those methods.
ArrayList can only store one type at a time, but the string, string, int represent the firstname, lastname, and birth year, so you can just instead interpret an ArrayList as a Person (ArrayList<Person>) instead of string, string, integer.
There is not much I can really tell you. Without knowing you're course I'm afraid I can't really say the best approach. When I took java, generics were covered before collections, but we covered manual collections like linkedLists and heaps before using the built in ones.
Old Pedant
12-06-2009, 11:00 PM
I don't see how this Java code is or should be any different than C# or VB.
Even in VB, you should have coded it this same way.
Almost identically, in fact.
Public Class Person
private _firstname AS String
private _lastname AS String
private _yearborn As Integer
public property FirstName As String
get
return _firstname
end get
set( name As String )
_fistname = name
end set
end property
... and so on ...
End Class
And then you would have a collection of Person objects in your PersonList (or "People" might be a better name).
Such as
Dim People As New List(Of Person)
So how is Java really any different than that???
mdnealy
12-07-2009, 12:57 AM
This program we are not using collection but either an Array or Arraylist. The user needs to input it. I am having trouble with the coding were you put the information in the array. I am told I cannot use one array list for firstname, lastname, and yearborn. but i see that you can store data in an array that has both an integer and string. my question was, how do i loop over the information to print out from the array once it is stored. These have to be done in separate steps.
step 1. enter names into database(array)
step 2 print out names that were entered
step 3 is search....don't care about that right now...
So, can someone tell me...simply since I am just at beginning stages, from my code, what needs to be rearranged, or if someone can give me an example of information inputted into an Arraylist then after a few inputs print out the list I would greatly appreciate it. The book doesn't show input or string just integers which should be the same but i just keep getting errors.
I use for loops in my printing and I am just doing something wrong or maybe it just a little fix of what I have.
Fou-Lu
12-07-2009, 02:56 AM
@oldPendant, slightly different approach in java since there are no properties like in C#/VB, but yes its about the same logically (which is what I was also getting at).
@mdnley, arrays and ArrayLists are both collections. A primitive array is just a primitive collection of data, but its still a collection (not of the Collection interface though). You are correct in assuming that you cannot use a single arrayList to contain the three pieces of data for two reasons: the first is because you would need to pull three items out to represent one object, and the other is because you would need to handle cast off of each object type if is not to be generic which is a pain.
For printing an ArrayList, there are several routes. The first is that you can extend the class itself and implement the toString method to take care of the iteration. The next is to use a standard for loop with:
for (int i = 0; i < myArrayList.size(); ++i)
{
System.out.println(myArrayList.get(i)); // You'll need to interpret this as necessary
}
You can also use the extended foreach in Java:
for (Person p : myPersonList)
{
System.out.println(p); // Interpret this as necessary.
}
ArrayList is a generic type. This means that you should provide it with the type of data it will store at instantiation rather than storing just Object and casting where necessary:
ArrayList<Person> pList = new ArrayList<Person>(); //Create a collection of Person
ArrayList<Double> dList = new ArrayList<Double>(); // Create a collection of Double
...
Placing data into an ArrayList simply uses the add method of Collection. So after instantiating you're collection, you simply invoke the .add method on it.
For input, a simple scanner will work:
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
ArrayList<Person> pList = new ArrayList<Person>();
System.out.println("First Name?");
String sFirst = s.nextLine();
System.out.println("Last Name?");
String sLast = s.nextLine();
System.out.println("Year Born?");
int iYear = s.nextInt();
pList.add(new Person(sFirst, Last, iYear));
}
Loop you're input for requests and keep adding to you're arrayList - pList. I doubt you'll need to worry about datatype validation or anything like that at this time in you're course, but scanner can throw InputMismatch, NoSuchElement and IllegalState exceptions (Exception is always at the end of Exception classes of course).
Old Pedant
12-07-2009, 07:01 AM
FouLa: Yes, I know no properties in Java. Sorry. Was just responding to your interface where you showed the moral equivalent in the form or your get and set methods. Just was trying to say that although the syntax may differ, all the concepts are exactly the same. He claimed to know VB.NET, so I (perhaps foolishly) assumed he understood about arrays and collections of objects.
I wonder if what the original poster is trying to say is that they aren't *ALLOWED* to use a single array of objects for this assignment and are supposed to use 3 parallel arrays. Personally, if that's really what the instuctor meant, I'd go find myself another instructor, fast.
But I think it equally likely that the original poster doesn't understand the assignment.
mdnealy
12-07-2009, 05:25 PM
I am a beginner in all the languages and was stating I didn't have this much trouble in vb or C#. but then I never had to do most of my stuff in console for vb. Java instructor seems to assume I understand which I have a good idea but when I put the code together error error error. lets start over. First here is the first part of the assignment...
Main Menu
WELCOME TO PERSON DATABASE!
Main Menu
1. Add a new Person to the database.
2. Print the database.
3. Search for a person in the database.
4. Exit the application.
Please enter your operation:
Add Person to the Database
Add Person to Database
Enter first name: Rita
Enter last name: Red
Enter year of birth: 1970
Print the Database
Last Name First Name Age
=================== =================== ===
Red Rita 39
Orange Oscar 22
above are the names provided by the user only..nothing set.
now, combining the information given here I came up with this code..except, it prints the information twice in case 2 and it is providing memory location but not the information. the program keeps making me go to static..
import java.util.Scanner;
public class Person {
static // private static String title;
// private static String menu;
Scanner input = new Scanner(System.in);
private static String first;
private static String last;
private static Integer year=0;
private static Integer age;
private static Integer selection;
public Person(String sFirst, String sLast,Integer iYear) {
setFirst(sFirst);
setLast(sLast);
setYear(iYear);
}
public void setFirst(String first) {
Person.first = first;
}
public static String getFirst() {
return first;
}
public void setLast(String last) {
Person.last = last;
}
public static String getLast() {
return last;
}
public void setYear(Integer year) {
Person.year = year;
}
public static Integer getYear() {
year= 2002-year;
return year;
}
public void setAge(Integer age) {
Person.age = age;
}
public static Integer getAge() {
age= 2002-year;
return age;
}
public static void getMainMenu() {
// TODO Auto-generated method stub
System.out.println("Main Menu\n1. Add a new Person to the database.\n2. Print the database.\n3. Search for a person in the database.\n4. Exit the application.");
}
public static int getSelection() {
System.out.println("Please enter selection:");
selection =input.nextInt();
return selection;
}
public static void getMainTitle() {
System.out.println("MAIN MENU\nWelcome to the Person Database\n");
}
}
and the test
import java.util.ArrayList;
import java.util.Scanner;
public class PersonTest
{
public static void main(String[] args )
{
ArrayList<Person> pList = new ArrayList<Person>();
Scanner s = new Scanner(System.in);
Person.getMainTitle();
Person.getMainMenu();
int selection;
System.out.println("Please enter selection\n");
selection = s.nextInt();
for(selection=0; selection <= 3; selection++)
{
switch(selection){
case 1: do
{System.out.println("Enter First Name");
String sFirst = s.next();
System.out.println("Enter Last Name");
String sLast = s.next();
System.out.println("Enter year of birth");
int iYear = s.nextInt();
pList.add(new Person(Person.getFirst(),Person.getLast(), Person.getYear()));
Person.getMainMenu();}
while (Person.getSelection()==1);
case 2: System.out.println("Last Name First Name Age ");
System.out.println("===================== ===================== ===");
for(int i =0; i<pList.size();i++){
System.out.println(pList.get(i));
// for(Person p: pList){
//
// System.out.println(p);
}
}
}
}
}
Old Pedant
12-07-2009, 07:16 PM
Okay, for starters, you should not have *ANY* static members of your Person class.
That's a killer.
When you have a static member (same as "SHARED" in VB.NET, by the by), it means you can only have *ONE* value for that field in you ENTIRE APPLICATION. So as soon as you assigned another value to one of those fields (for example, called setFirst method) you WIPE OUT the prior value and remember only the latest one.
Secondly, you should not mix the I/O with the data storage. Meaning you should not have the methods getMainMenu(), getSelection(), or getMainTitle() in your Person class.
I would start with this as your Person class:
public class Person
{
private String first;
private String last;
private Integer age;
public Person(String sFirst, String sLast,Integer iYear)
{
setFirst(sFirst);
setLast(sLast);
setYear(iYear);
}
public void setFirst(String first) {
this.first = first;
}
public String getFirst() {
return this.first;
}
public void setLast(String last) {
this.last = last;
}
public String getLast() {
return this.last;
}
public void setAge(Integer age) {
this.age = age;
}
public Integer getAge() {
return this.age;
}
public String toString() {
return "First name: " + first + "\nLast name: " + last + "\nAge: " + age;
}
}
I left out getYear() because I don't understand the purpose of it. Certainly don't understand why it would be related to the constant 2002 when the current year is 2009. But other than that, there should be nothing else in that class.
The toString() method is intended for debugging, but it might be adequate for your first purposes in this assignment.
Now, you should have a primary class, with the main() method, that you use for inputting requests from the user, such as for adding a person or finding and displaying a person. But don't mix that up with the Person class.
mdnealy
12-07-2009, 07:26 PM
you need to get the year the person was born from the user than convert it to age when you print out the list of people
Old Pedant
12-07-2009, 07:41 PM
Okay, then something like this?
public class Person
{
private String first;
private String last;
private Integer yearborn;
public Person(String sFirst, String sLast,Integer iYear)
{
setFirst(sFirst);
setLast(sLast);
setYear(iYear);
}
public void setFirst(String first) {
this.first = first;
}
public String getFirst() {
return this.first;
}
public void setLast(String last) {
this.last = last;
}
public String getLast() {
return this.last;
}
public void setBirthYear(Integer year) {
this.yearborn = year;
}
public Integer getBirthYear() {
return this.yearborn;
}
public Integer getAge() {
// would be better to use a Java function to get current date
// and figure out the right age from that, but this will get you started:
return 2009 - this.yearborn;
}
public String toString() {
return "\nFirst name: " + first
+ "\nLast name: " + last
+ "\nYear born: " + yearborn
+ "\nAge: " + this.getAge();
}
}
Old Pedant
12-07-2009, 07:43 PM
To impress the instructor, you should get the actual Date of Birth (DOB) and then calculate actual age.
For example, if person was born November 7, 2000, then age today is 9. If born December 30, 2000, then age today is still 8.
But that's later. Get the basic stuff working, first.
mdnealy
12-07-2009, 08:08 PM
okay, still working on the print method for case 2 but how do I get the conversion to the year to age..do i put it in the set? or get?
public Integer getYear(){
year = 2009- year;
return this.year;
}
no errors but it still returns the year not the age.
for the printing this is what i am getting:(the ='s are fillers because i have to have the original heading. it prints out twice.
Last Name First Name Age
===================== ===================== ===
mm=================== mm=================== 12
nn=================== nn=================== 45
Last Name First Name Age
===================== ===================== ===
mm=================== mm=================== 12
nn=================== nn=================== 45
My code in person is..
public String toString() {
return "" + last + "=================== " + first + "=================== " + year;
and in test case 2:
case 2: System.out.println("Last Name First Name Age ");
System.out.println("===================== ===================== ===");
for(int i =0; i<pList.size();i++){
System.out.println(pList.get(i));
so now what am i doing wrong...
Old Pedant
12-07-2009, 08:15 PM
Why are you surprised you are still getting year when that's what you coded???
public String toString() {
return "" + last
+ "=================== "
+ first + "=================== "
+ year;
}
If you don't want year, don't use that in your code.
I showed you that you could call this.getAge() in your toString().
Dunno why you are getting the stuff twice. I don't have your most recent code to look at.
mdnealy
12-07-2009, 08:32 PM
Okay, so my array is working...missed the part about the age..got that fixed when it prints out I need it to look like:
Last Name First Name age
============ ======== ===
last name first name age
last name first name age
I tried to change the return to a system out print f but that didn't work...
her is the update program:
import java.util.Scanner;
public class Person
{
private String first;
private String last;
private Integer year;
private static Integer selection;
public Person(String sFirst, String sLast,Integer iYear)
{
setFirst(sFirst);
setLast(sLast);
setYear(iYear);
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getYear() {
return this.year;}
public void setFirst(String first) {
this.first = first;
}
public String getFirst() {
return this.first;
}
public void setLast(String last) {
this.last = last;
}
public String getLast() {
return this.last;
}
public Integer getAge() {
// would be better to use a Java function to get current date
// and figure out the right age from that, but this will get you started:
return 2009 - this.year;
}
// int age= 2009- year;
public String toString() {
return "" + last + "== " + first + "== " + this.getAge();
//return "First name: " + first + "\nLast name: " + last + "\nAge: " + age;
}
public static void getMainMenu(){
// TODO Auto-generated method stub
System.out.println("Main Menu\n1. Add a new Person to the database.\n2. Print the database.\n3. Search for a person in the database.\n4. Exit the application.");
}
static Scanner input= new Scanner(System.in);
public static Integer getSelection() {
System.out.println("Please enter selection:");
selection =input.nextInt();
return selection;
}
public static void getMainTitle() {
System.out.println("MAIN MENU\nWelcome to the Person Database\n");
}
}
and the test
import java.util.ArrayList;
import java.util.Scanner;
public class PersonTest
{
public static void main(String[] args )
{
ArrayList<Person> pList = new ArrayList<Person>();
Scanner s = new Scanner(System.in);
Person.getMainTitle();
Person.getMainMenu();
int selection;
System.out.println("Please enter selection\n");
selection = s.nextInt();
for(selection=0; selection <= 3; selection++)
{
switch(selection){
case 1: do
{System.out.println("Enter First Name");
String sFirst = s.next();
System.out.println("Enter Last Name");
String sLast = s.next();
System.out.println("Enter year of birth");
int iYear = s.nextInt();
pList.add(new Person(sFirst, sLast, iYear));
Person.getMainMenu();}
while (Person.getSelection()==1);
case 2: System.out.println("Last Name First Name Age ");
System.out.println("===================== ===================== ===");
for(int i =0; i<pList.size();i++){
System.out.println(pList.get(i));
// for(Person p: pList){
//
// System.out.println(p);
}
}
}
}
}
Old Pedant
12-07-2009, 09:15 PM
I don't at all understand the point of this code:
System.out.println("Please enter selection\n");
selection = s.nextInt();
for(selection=0; selection <= 3; selection++)
You *ask* for the selection, but then you completely ignore it!
And, further, you loop from 0 to 3 for the value of selection, but your switch() only handles values 1 and 2. So 0 and 3 in the loop do nothing at all.
Further. in case 1, you have the loop
do { ... } while ( Person.getSelection() ==1 );
And that's again very bad design. I will say again: You should have NO STATIC MEMBERS in your Person class.
You need to separate data from presentation from control. It's called "MVC design" which stands for "Model-View-Controller". Typically, you would have one class for the Model--in your case the Person class. One class for the Controller. In your case the PersonTest class. And--missing from your code--one class for the presentation. You are using static members of your Person class for the View. Bad choice.
For this simple little program, it wouldn't be terrible to combine the View and the Controller, meaning you could move all the static members from Person to PersonTest. But even for this program, I wouldn't combine View and Model. (You could argue that even the toString() method in Person violates this, but I think it's acceptable for this case.) But why not do it "right" and create a "PersonView" class? Would surely impress your instructor, too.
So now your PersonTest class might be as simple as:
public class PersonTest
{
public static void main( String[] args )
{
ArrayList<Person> pList = new ArrayList<Person>( );
while ( true ) /* forever */
{
System.out.println("What do you want to do?\n"
+ "A==Add a person, S==Show all, F==Find, X==Exit\n");
String choice = s.next( );
if ( choice.equals("X") ) break; // out of the loop...program is done
if ( choice.equals("A") )
{
... prompt to get data for one person ...
... create a new Person ...
... add it to pList ...
} else if ( choice.equals("S") ) {
... dump out all the entries in pList ...
} else if ( choice.equals(F") ) {
... code not yet written to do the Find ...
}
} // end of the infinite loop
} // end of main
}
So if you do create a PersonView class, it should have the methods for collecting the info about one person and then creating the Person object. And it should have the method(s?) for displaying one person.
Leaving only the "control" to PersonTest, which might now well be renamed PersonControl.
Old Pedant
12-07-2009, 09:17 PM
Incidentally, your loop, as now designed, doesn't allow the person to add more entries after showing all. Or, presumably, after doing a find. So the loop, as written, really *must* go.
mdnealy
12-09-2009, 03:46 AM
thanks i haven't finished with this though i had to turn in what i had but i am bound and determined to make it work. have to do another project due in 1 week and i will need all my time for that!!! thanks again for your help. I am sure i will continue this thread soon/
mdnealy
12-10-2009, 09:47 AM
okay, i got my arraylist working and can print out my list. now for the search. I am attaching my code but I am sure I am way off.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class DataBase {
private ArrayList<Person> personList;
public DataBase(){
personList = new ArrayList<Person>();
}
public void add(Person p){
personList.add(p);
}
public void print()
{
System.out.printf("%s %22s %15s\n", "LastName", "FirstName", "Age");
System.out.printf("%s %s %s\n","=================== ", "=================== ", "===");
for (Person p: personList){
System.out.printf("%s %22s %17d\n", p.getLastName(), p.getFirstName(), p.getAge());
}
int size = personList.size();
for (int i=0; i<size; i++) {
System.out.println("People are:" + i + personList.get(i));
}
Collections.sort(personList);
for (int i=0; i<size; i++) {
System.out.println("" + i + personList.get(i));
}
i need to be able to get input for what the person is looking for in firstname, lastname, or age. how do I change this and sort. is errored.
Old Pedant
12-10-2009, 06:49 PM
Naw, you are off in the wrong direction.
Rethink this from a TOP DOWN view point. Figure out the tasks you need to do, write the top level code to invoke those tasks--without any codd to actually perform them. *THEN* go in and starting to write the code to perform one task.
See the outline I gave you in post # 17.
mdnealy
12-10-2009, 07:30 PM
I have that code. I have two other classes that i didn't post that take care of getting the name and printing it. it all works great.. what i should have mentioned at the bottom of the code I did post was a search. I am not sure how to go back through the code that I do have and search for a name. I found some stuff on line and in the book but i am not sure how to make it work. I need to have the user input what part they want to look for, firstname last name or age and i need to be able to go find it. what syntax for an array list is good to do this job? i should have highlighted the last few lines of code...that is where i am having trouble. I can get the user input but i am having trouble with the code to find it.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.