6 Replies - 481 Views - Last Post: 25 January 2013 - 07:09 PM Rate Topic: -----

#1 fatmark801  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 25-January 13

Cannot search ArrayList in Java

Posted 25 January 2013 - 01:43 PM

I have to create an ArrayList of students which will store their first and last name, a student number, a major, and their gpa. I have the program working but I have to be able to search the array for a student based off user input and this is what I can't figure out. In class StudentList under method findStudent() I am trying to search through an ArrayList of what (I believe) is type Student and I am trying to search with a string.

I have tried many things such as simply trying to search using contains with and without loops, unsuccessfully attempted to convert the list to string via toString() and a StringBuilder. No matter how I set it up, it either won't compile or if it does, not matter what it returns false.

I attempted to comment out all the code that didn't work and erased it when it got to long figuring I would get it eventually and now realized that was a mistake as I cannot share with you all the mistaken ways I have been unable to find something in an arraylist. If anyone could point in the right direction I would greatly appreciate it.

public class Student{

	//instance variables
	private String studentFirstName;
	private String studentLastName;
	private int studentNumber;
	private String studentMajor;
	private double studentGPA;
	static int count;

	public Student( String first, String last, int number, String major, double gpa ){
		studentFirstName = first;
		studentLastName = last;		
		studentNumber = number;
		studentMajor = major;
		studentGPA = gpa;
		
		count++;
		}//end constructor
	
	public void setFirstName( String first ){
		studentFirstName = first;
	}//set studentName
	
	public String getFirstName(){
		return studentFirstName;
	}//return studentName
	
	public void setLastName( String last ){
		studentLastName = last;
	}//set studentName
	
	public String getLastName(){
		return studentLastName;
	}//return studentName

	public void setId( int number ){
		if ( number >= 0 ){
			studentNumber = number;
		}
		else
			throw new IllegalArgumentException(
				"Students number must be a positive whole number." );
	}//set studentNumber


	public int getNumber(){
		return studentNumber;
	}//return studentNumber
	
	public void setMajor( String major ){
		studentMajor = major;
	}//set studenttMajor
	
	public String getMajor(){
		return studentMajor;
	}//return studentMajor
	
	public void setGPA( double gpa ){
		if ( gpa >= 0.0 && gpa <= 4.0 ){
			studentGPA = gpa;
		}
		else
			throw new IllegalArgumentException(
				"Students GPA must be a positive number greater that or equal to 0\nand less than or equal to 4." );
	}//set studentGPA
	
	public double getGPA(){
		return studentGPA;
	}//get studentGPA
	
	@Override//overrides toString from class object
	public String toString(){
		return String.format( "        %-14s%-13s%-12d%-20s%-6.1f", getFirstName(), getLastName(), getNumber(),
		getMajor(), getGPA() );
	}//end toSting method

}//end class Student




import java.util.ArrayList;
import java.util.Scanner;

public class StudentList{
	Scanner keyBd = new Scanner( System.in );
	
	ArrayList<Student> list = new ArrayList<Student>(); //initialize ArrayList
	
	//instance variables
	private String first;
	private String last;
	private int number;
	private String major;
	private double gpa;
	private String search;
	private int arrayid;
	private char selection;
	
	public void addStudent(){		
		System.out.println("\n Add a student to list");
		System.out.print("Enter a students first name: ");
			first = keyBd.next();
		System.out.print("Enter that students last name: ");
			last = keyBd.next();
		System.out.print("Enter that students number: ");
			number = keyBd.nextInt();
		System.out.print("Enter that students Major\n(Separate words with an underscore _): ");
			major = keyBd.next();
		System.out.print("Enter that students GPA: ");
			gpa = keyBd.nextDouble();
		Student newStudent = new Student(first, last, number, major, gpa);
		
		list.add(newStudent);		
	}//end addStudent
	 
	public Student findStudent(){
		System.out.print( "Enter term to search by:\n" );
			search = keyBd.next();
		Student found=null;

		for ( Student st : list ){
			if(this.list.contains(search)){
				int index = this.list.indexOf(search);
				found = this.list.get(index);
			}	
		}		
		return found;	

	}//end findStudent

	public void removeStudent(){		
		System.out.println("\n Remove a student:");
		System.out.println("Enter the students list number you would like to remove: ");
			arrayid = keyBd.nextInt();
		if(arrayid >= 1)	{
			list.remove(arrayid-=1);
		}
	}//end removeStudent


	public void displayList(){		
		if(list.size() > 0){
			System.out.printf("%-9s%-14s%-13s%-12s%-20s%-6s\n", "Number", "First Name", "Last Name", "Student #",
				"Major", "GPA" );
			
			for(int i = 0; i < list.size(); i++){
				System.out.printf("%d%-9s\n", i+1, list.get(i));
			}
		}
		else
			System.out.println( "Student list currently empty" );	
	}//end displayList
	
	public void displaySize(){
		System.out.printf( "Total Number of Students Currently in List: %d\n", list.size() );
		System.out.printf( "Total Students Created: %d", Student.count );
	
	}//end displayList
	
	public void studentMenu(){
		char selection;//capture variable

		do{//display menu
			System.out.println("\n**************");
			System.out.println("Student List");
			System.out.println("--------------");
			System.out.println("1. Add Student");
			System.out.println("2. Find Student");
			System.out.println("3. Remove Student");
			System.out.println("4. Display List");
			System.out.println("5. Display Total Number Of Students");
			System.out.println("6. Exit\n");
			System.out.print  ("Selection: ");

			selection = keyBd.next().charAt(0);
			//get menu selection

			switch (selection){//process menu selection
				case '1':
					addStudent();
					break;
				case '2':
					findStudent();
					break;
				case '3':
					removeStudent();
					break;
				case '4':
					displayList();
					break;
				case '5':
					displaySize();
					break;
				case '6':
					break;
				default :
					System.out.println("Invalid Selection");
			}//end switch

		}while( selection != '6');//while selections is not 4, 4 ends menu which stops program
	}//end studentMenu()

}//end class StudentList



public class StudentApp{

	public static void main( String args[] ){//main declaration{
		StudentList studentList = new StudentList();
		studentList.studentMenu();
	}//end main()

}//end class StudentApp



Is This A Good Question/Topic? 0
  • +

Replies To: Cannot search ArrayList in Java

#2 NathanMullenax  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 83
  • View blog
  • Posts: 176
  • Joined: 23-September 12

Re: Cannot search ArrayList in Java

Posted 25 January 2013 - 02:03 PM

You seem to have an ArrayList of student objects, but you're comparing the individual elements to strings, doubles, and ints.

You'll have to loop through the list of students, extract the appropriate field from each student object, and then compare on that. If you convert an object without an overridden ToString method, you'll get a memory address or something like that.

Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#3 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2198
  • View blog
  • Posts: 5,226
  • Joined: 10-September 10

Re: Cannot search ArrayList in Java

Posted 25 January 2013 - 02:21 PM

You have an ArrayList of Student objects, ArrayList<Student>, called list (nice name, why not studentList?). The structure kind of looks like:

For the first student object in the list:

list.Student1.first
list.Student1.last
list.Student1.number
list.Student1.major
list.Student1.gpa

For the second object in the list:

list.Student2.first
list.Student2.last
list.Student2.number
list.Student2.major
list.Student2.gpa

and so on.

The user is asked to enter a search term. I assume that means the user can input anything, a String for either the first name, last name, or major, an int for the student number, or a double for the gpa. Is that right?

However you decide to accept the search term, you then search the Student objects in the list for the term.
So you need Student methods to locate the right Student. Let's say you know you're looking for the student object's first name, "Steve". You'd create a Student method:
public String getFirst()
{
    return first;
}

Then you could check each Student object in the list:
if ( list.get( index ).getFirst().equals( "Steve" )
{
    // do what you do when you find a list
    // member with the desired name
}

Based on the way you've written the program so far, the hard part will be determining which characteristic of Student to search for, or check all of them figuring out how to normalize or adjust for the type of item you're searching for.

This post has been edited by GregBrannon: 25 January 2013 - 02:22 PM

Was This Post Helpful? 3
  • +
  • -

#4 fatmark801  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 25-January 13

Re: Cannot search ArrayList in Java

Posted 25 January 2013 - 02:27 PM

Nathan and Greg I appreciate both of your inputs on the situation. I will give them both a go and I will let you know if it worked, thanks again.
Was This Post Helpful? 0
  • +
  • -

#5 fatmark801  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 25-January 13

Re: Cannot search ArrayList in Java

Posted 25 January 2013 - 06:42 PM

Well I just finished some other course work and finally figured it all out, thank you again for your help! Was starting to get a little frustrated but not anymore.

Incase you are curious this is what I did.

Also, know of anyway I can edit my original post so nobody jacks my code? I assume many of colleges have this or similar assignments and I don't want anyone to cheat off of it.

	public void findStudent(){
	 	System.out.print("Please enter term you wish to search by:");
		search = keyBd.next();
		
		String[] result = new String[list.size()]; 
		for (int i = 0; i < list.size(); i++){ 
			String x = list.get(i).toString();
				if (x.contains(search)){
			 		System.out.printf("The term %s was found in your list of students.", search);
				}
				
		}
	}//end findStudent


Was This Post Helpful? 0
  • +
  • -

#6 NathanMullenax  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 83
  • View blog
  • Posts: 176
  • Joined: 23-September 12

Re: Cannot search ArrayList in Java

Posted 25 January 2013 - 06:52 PM

View Postfatmark801, on 25 January 2013 - 06:42 PM, said:

Also, know of anyway I can edit my original post so nobody jacks my code? I assume many of colleges have this or similar assignments and I don't want anyone to cheat off of it.


I wouldn't worry about it too much. It's going to be similar to a lot of things that people are assigned; hopefully it is helpful to other people. As far as outright plagiarism, most professors have mechanisms to find it. Also, it seems so generic as to be unsearchable. I mean, if someone searched something like 'student class search homework help', this wouldn't even show up--sites that sell homework would.

There is an 'edit post' option, but it might not show up until you've made a certain number of posts or something--I'm not sure. But again, I really wouldn't worry about it.
Was This Post Helpful? 1
  • +
  • -

#7 fatmark801  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 25-January 13

Re: Cannot search ArrayList in Java

Posted 25 January 2013 - 07:09 PM

Alright then I won't worry about it. Yeah, I see no edit post option currently.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1