Results 1 to 2 of 2
  1. #1
    kubera is offline Member
    Join Date
    Apr 2012
    Posts
    1
    Rep Power
    0

    Default How to convert my code from LinkedList to HashSet

    I'm having trouble converting my code from LinkedList to HashSet. I'm not for sure how to make my functions work after the switch.

    Java Code:
    //Programmer: Dylan Helpling
    //Project 3
    //Date: 4/16/2012
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    import javax.swing.JOptionPane;
    import java.io.PrintWriter;
    import java.util.Set;
    import java.util.Iterator;
    
    public class StudentTester {
    
    	static Set students = new HashSet(101);// Declaring my hashset outside main
    											// method
    
    	public static void main(String[] args) throws FileNotFoundException {
    
    		String inputFileName = JOptionPane
    
    		.showInputDialog(null, "Input File: ");
    
    		File inputFile = new File(inputFileName);
    
    		while (true) {
    
    			String num = JOptionPane.showInputDialog(
    
    			"Choose\n1   " +
    
    			"Add a New Student\n2   " +
    
    			"Remove a Student\n3   " +
    
    			"Update Roster\n4   " +
    
    			"Search Option\n5   " +
    
    			"Student Roster\n6   " +
    
    			"Exit");
    
    			if (num.equals("1")) {// Method to add student
    				
    			int comparisons = 0;
    			comparisons++;
    
    				Scanner viewer = new Scanner(inputFile);
    
    				while (viewer.hasNext()) {
    					int id = viewer.nextInt();
    
    					String name = viewer.next();
    
    					double gpa = viewer.nextDouble();
    
    					students.add(new Student(id, name, gpa));
    				}
    				viewer.close();
    
    				while (true) {
    
    					int id = Integer
    							.parseInt(JOptionPane
    									.showInputDialog("Enter the ID of the New Student:"));
    
    					String name = JOptionPane
    							.showInputDialog("Enter the Name of the New Student:");
    
    					double gpa = Double
    							.parseDouble(JOptionPane
    									.showInputDialog("Enter the GPA of the New Student:"));
    
    					students.add(new Student(id, name, gpa));
    					JOptionPane.showMessageDialog(null,
    							"Number of comparisons" + comparisons);
    					break;
    
    				}
    
    			}
    
    			else if (num.equals("2")) {// Method to remove student
    
    				String sLastName = (JOptionPane
    						.showInputDialog("Enter the Last name of the student you want removed:"));
    				int comparisons = 0;
    				comparisons++;
    				Scanner viewer = new Scanner(inputFile);
    
    				while (viewer.hasNext())
    
    				{
    
    					int id = viewer.nextInt();
    
    					String name = viewer.next();
    
    					double gpa = viewer.nextDouble();
    
    					students.add(new Student(id, name, gpa));
    
    				}
    
    				viewer.close();
    
    				boolean found = false;
    				
    			
    
    				for (int i = 0; i < students.size(); i++)
    
    				{
    					Iterator iter = students.iterator();
    					
    					while (iter.hasNext())
    						
    						if (iter.equals(sLastName.hashCode()))
    
    						{
    
    							iter.remove();
    							
    							JOptionPane.showMessageDialog(null,
    									"Student removed");
    
    							found = true;
    
    							break;
    
    						}
    
    				}
    
    				if (!found)
    
    				{
    
    					JOptionPane.showMessageDialog(null,
    							"No student with that Last Name");
    
    				}
    				
    
    			}
    
    			else if (num.equals("3"))// Method update students
    
    			{
    				String sId = (JOptionPane						.showInputDialog("Enter the ID of the student you want to update:"));
    
    				Scanner viewer = new Scanner(inputFile);
    				int comparisons = 0;
    
    				Student s1 = null;
    
    				int listNode = 0;
    
    				while (viewer.hasNext())
    
    				{
    
    					int id = viewer.nextInt();
    
    					String name = viewer.next();
    
    					double gpa = viewer.nextDouble();
    
    					students.add(new Student(id, name, gpa));
    
    				}
    
    				viewer.close();
    
    				boolean found = false;
    
    				for (int i = 0; i < students.size(); i++) {
    
    					Iterator iter = students.iterator();
    
    					while (iter.hasNext())
    
    						if (iter.equals(sId.hashCode())){
    
    							if (iter.next(getId()) == sId) {
    
    								s1 = iter.next();
    
    								listNode = i;
    
    								found = true;
    							
    
    								break;
    
    							}
    
    				}
    
    				if (!found)
    					break;
    
    				String update = JOptionPane
    						.showInputDialog("What do you want to update: \n" +
    
    						"ID - 1 \n" +
    
    						"Name - 2 \n" +
    
    						"GPA - 3");
    
    				update = update.toUpperCase();
    
    				if (update.equals("1"))// update ID
    
    				{
    					int newId = Integer
    							.parseInt(JOptionPane
    									.showInputDialog("Enter the new ID of the student: "));
    
    					boolean same = false;
    
    					for (int i = 0; i < students.size(); i++)
    
    					{
    						if (students.get(i).getId() == newId)
    
    						{
    
    							JOptionPane.showMessageDialog(null,
    									"There is a student with that ID: "
    											+ students.get(i).toString());
    
    							same = true;
    
    							break;
    						}
    					}
    
    					if (!same)
    
    					{
    						students.add(
    								listNode,
    								new Student(newId, s1.getLastName(), s1
    										.getGpa()));
    					}
    				}
    
    				else if (update.equals("2")) {// update name
    					String newName = JOptionPane
    							.showInputDialog("Enter new name for student: ");
    
    					students.set(
    							listNode,
    							new Student(s1.getId(), newName.trim(), s1.getGpa()));
    				}
    
    				else if (update.equals("3")) {// Update GPA
    					double newGpa = Double.parseDouble(JOptionPane
    							.showInputDialog("Enter new GPA for student: "));
    
    					students.set(listNode,
    							new Student(s1.getId(), s1.getLastName(), newGpa));
    				}
    
    			}
    
    			else if (num.equals("4"))// Method for searching
    
    			{
    
    				Scanner viewer = new Scanner(inputFile);
    
    				while (viewer.hasNext())
    
    				{
    					int id = viewer.nextInt();
    
    					String name = viewer.next();
    
    					double gpa = viewer.nextDouble();
    
    					students.add(new Student(id, name, gpa));
    				}
    
    				viewer.close();
    
    				String search = JOptionPane.showInputDialog(
    
    				"How would you like to search: \n" + "ID - 1 \n"
    						+ "Name - 2 \n" + "GPA - 3");
    
    				if (search.equals("1"))// Search by ID
    
    				{
    
    					int id = Integer.parseInt(JOptionPane
    							.showInputDialog("Enter the ID of the student: "));
    
    					boolean found = false;
    
    					
    						if (students.contains(id)){
    					
    
    						{
    							JOptionPane.showMessageDialog(null,
    									"Student Found");
    
    							found = true;
    
    							break;
    						}
    					
    
    					if (!found) {
    						JOptionPane.showMessageDialog(null,
    								"No student has that ID");
    					}
    				}
    				}
    
    				else if (search.equals("2")) {// Search by Name
    					String name = JOptionPane
    							.showInputDialog("Enter the name of the student: ");
    
    					boolean found = false;
    
    					
    
    					
    
    						if (students.contains(name)){
    
    						{
    
    							JOptionPane.showMessageDialog(null,
    									"Student Foun");
    
    							found = true;
    
    							break;
    
    						}
    						
    					
    				
    					
    
    					if (!found)
    
    					{
    
    						JOptionPane.showMessageDialog(null,
    								"No student has that name");
    
    					}
    
    				}
    					}
    				
    				else if (search.equals("3")) {// Search by GPA
    					double gpa = Double.parseDouble(JOptionPane
    							.showInputDialog("Enter the GPA of the student: "));
    
    					boolean found = false;
    
    					
    
    					if (students.contains(gpa)){
    
    							found = true;
    
    						}
    
    					
    
    					if (found)
    
    						JOptionPane.showMessageDialog(null,
    								"Student(s) Found");
    
    					else
    
    						JOptionPane.showMessageDialog(null,
    								"There is no student(s) with that GPA");
    
    				}
    
    				else
    
    				{
    
    					JOptionPane.showMessageDialog(null, "Invalid search");
    
    				}
    
    			} else if (num.equals("5")) {
    
    				Scanner in = new Scanner(inputFile);
    
    				String list1 = "";
    
    				while (in.hasNext()) {
    
    					list1 += in.nextLine();
    
    					list1 += "\n";
    
    				}
    
    				JOptionPane.showMessageDialog(null, "Students: \n" + list1);
    
    				in.close();
    
    			}
    
    			else if (num.equals("6"))
    
    			{
    
    				Scanner viewer = new Scanner(inputFile);
    
    				while (viewer.hasNext())
    
    				{
    					int id = viewer.nextInt();
    
    					String name = viewer.next();
    
    					double gpa = viewer.nextDouble();
    
    					students.add(new Student(id, name, gpa));
    
    				}
    
    				viewer.close();
    
    				File list = new File("List.txt");
    
    				PrintWriter out = new PrintWriter(list);
    
    				for (int i = 0; i < students.size(); i++)
    
    				{
    
    					out.println(students.get(i).toString());
    
    				}
    
    				out.close();
    			}
    
    			else if (num.equals("7"))// Exit
    			{
    				return;
    			}
    
    			else {
    				JOptionPane.showMessageDialog(null, "Invalid Choice");
    			}
    
    		}
    
    	}

    Then this is my other two classes, one is for students and the other implements Hashset

    Java Code:
    public class Student {
    	private int id;
    	private String lastName;
    	private double gpa;
    
    	Student() {
    		id = 0;
    		lastName = "";
    		gpa = 0;
    	}
    
    	Student(int iniid, String inilastName, double inigpa) {
    		id = iniid;
    		lastName = inilastName;
    		gpa = inigpa;
    
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public int getId() {
    		
    		return this.id;
    	}
    
    	public void setLastName(String lastName) {
    		this.lastName = lastName;
    	}
    
    	public String getLastName() {
    		return this.lastName;
    	}
    
    	public void setGpa(double gpa) {
    		this.gpa = gpa;
    	}
    
    	public double getGpa() {
    		return this.gpa;
    	}
    
    	public String toString() {
    		return id + "  " + lastName + "  " + gpa;
    	}
    	
    	public boolean equals(Object otherObject){
    		if (otherObject == null) return false;
    		if (getClass() != otherObject.getClass()) return false;
    		Student other= (Student) otherObject;
    		return hashCode() == other.hashCode() && lastName.equals(other.lastName);
    	}
    
    	public int hashCode() {
    
    		int n = lastName.hashCode();
    
    		return n;
    	}
    
    
    }
    Java Code:
    import java.util.AbstractSet;
    import java.util.Iterator;
    import java.util.NoSuchElementException;
    
    /**
       A hash set stores an unordered collection of objects, using
       a hash table.
    */
    public class HashSet extends AbstractSet
    {
       private Node[] buckets;
       private int size;
    
       /**
          Constructs a hash table.
          @param bucketsLength the length of the buckets array
       */
       public HashSet(int bucketsLength)
       {
          buckets = new Node[bucketsLength];
          size = 0;
       }
    
       /**
          Tests for set membership.
          @param x an object
          @return true if x is an element of this set
       */
       public boolean contains(Object x)
       {
          int h = x.hashCode();
          if (h < 0) h = -h;
          h = h % buckets.length;
          
          Node current = buckets[h];
          while (current != null)
          {
             if (current.data.equals(x)) return true;
             current = current.next;
          }
          return false;
       }
    
       /**
          Adds an element to this set.
          @param x an object
          @return true if x is a new object, false if x was
          already in the set
       */
       public boolean add(Object x)
       {
          int h = x.hashCode();
          if (h < 0) h = -h;
          h = h % buckets.length;
          
          Node current = buckets[h];
          while (current != null)
          {
             if (current.data.equals(x)) 
                return false; // Already in the set
             current = current.next;
          }
          Node newNode = new Node();
          newNode.data = x;
          newNode.next = buckets[h];
          buckets[h] = newNode;
          size++;
          return true;
       }
    
       /**
          Removes an object from this set.
          @param x an object
          @return true if x was removed from this set, false
          if x was not an element of this set
       */
       public boolean remove(Object x)
       {
          int h = x.hashCode();
          if (h < 0) h = -h;
          h = h % buckets.length;
          
          Node current = buckets[h];
          Node previous = null;
          while (current != null)
          {
             if (current.data.equals(x)) 
             {
                if (previous == null) buckets[h] = current.next;
                else previous.next = current.next;
                size--;
                return true;
             }
             previous = current;
             current = current.next;
          }
          return false;
       }
    
       /**
          Returns an iterator that traverses the elements of this set.
          @return a hash set iterator
       */
       public Iterator iterator()
       {
          return new HashSetIterator();
       }
    
       /**
          Gets the number of elements in this set.
          @return the number of elements
       */
       public int size()
       {
          return size;
       }
    
       class Node
       {
          public Object data;
          public Node next;
       }
    
       class HashSetIterator implements Iterator
       {
          private int bucket;
          private Node current;
          private int previousBucket;
          private Node previous;
    
          /**
             Constructs a hash set iterator that points to the
             first element of the hash set.
          */
          public HashSetIterator()
          {
             current = null;
             bucket = -1;
             previous = null;
             previousBucket = -1;
          }
          
          public boolean hasNext()
          {
             if (current != null && current.next != null) 
                return true;
             for (int b = bucket + 1; b < buckets.length; b++)
                if (buckets[b] != null) return true;
             return false;
          }
           
          public Object next()
          {
             previous = current;
             previousBucket = bucket;
             if (current == null || current.next == null) 
             {
                // Move to next bucket
                bucket++;
    
                while (bucket < buckets.length 
                      && buckets[bucket] == null)
                   bucket++;
                if (bucket < buckets.length) 
                   current = buckets[bucket];
                else
                   throw new NoSuchElementException();
             }
             else // Move to next element in bucket
                current = current.next; 
             return current.data;
          }
    
          public void remove()
          {
             if (previous != null && previous.next == current)
                previous.next = current.next;
             else if (previousBucket < bucket) 
                buckets[bucket] = current.next; 
             else
                throw new IllegalStateException();
             current = previous;
             bucket = previousBucket;
          }
       }
    }

  2. #2
    Diargg is offline Senior Member
    Join Date
    Feb 2012
    Posts
    117
    Rep Power
    0

    Default Re: How to convert my code from LinkedList to HashSet

    2 suggestions:
    1: That's a lot of code. Strip it down to the bare minimum so that was can follow it easily.
    2: What are the functions that aren't working? What are the error messages you received? Give more information so that it's easier to help you.

Similar Threads

  1. Convert C++ code to Java
    By napoleon in forum New To Java
    Replies: 2
    Last Post: 03-07-2010, 08:44 AM
  2. Convert java code to midlet code
    By coldvoice05 in forum New To Java
    Replies: 1
    Last Post: 08-12-2009, 12:14 PM
  3. Convert java code to midlet code
    By coldvoice05 in forum Advanced Java
    Replies: 1
    Last Post: 08-09-2009, 02:21 PM
  4. Convert bar code to number
    By samatha_kudi in forum Advanced Java
    Replies: 1
    Last Post: 07-17-2009, 03:56 PM
  5. how to convert source code to xml
    By valery in forum XML
    Replies: 2
    Last Post: 08-06-2007, 09:29 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •