Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 1 of 1

Thread: exception in thread main java.lang.Nullpointerexception

  1. #1
    Junior Member
    Join Date
    Feb 2011
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default exception in thread main java.lang.Nullpointerexception

    Hey everybody! I am a newbie here and a newbie at Java. I take a course at the university in Java programming. And I'm having some issues with my program. Wonder if any of the gurus in here might help me?

    You can see from the test-file how the whole system should work...


    Code in file Oblig1.java:


     
     
    public class Oblig1 {
     
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) throws Exception  {
    		if (args.length == 0) {
    			System.out.println("INF1010 - Oblig 1");
    			System.out.println("Usage:");
    			System.out.println("Run the tests: java Oblig1 test");
    			System.out.println("Run the shell: java Oblig1 shell");
    		}
    		else if (args[0].equals("test")) {
     
    			System.out.println("Comment in the test code and compile with the test file to run the tests.");
     
    			PersonList personlist = new PersonList();			
    			Oblig1Tests tester = new Oblig1Tests(personlist);
    			tester.runTests();
     
    		}
    		else if (args[0].equals("shell")) {
    			System.out.println("Create code to start your shell here.");
    		}
     
    	} // Close main 
     
    } // Close Oblig1
     
    class Person {
    	private String name, phone;
    	Person next, previous;
    	PersonList friends;
     
    	Person(){
    	System.out.println("No input given. Try again");
    	}
     
    	Person(String name){
    		this.name = name;
    	}
     
    	Person(String name, String phone){
    		this.name = name;
    		this.phone = phone;
    	}
        /**
         * Get the name of the person
         * @return   name of the person
         */
        public String getName(){
    	return name;
    	}
     
        /**
         * Get the phone number of the person
         * @return    phone number to the person
         */
        public String getPhone(){
    	if (phone == null) phone = "none";
    	return phone;
    	}
     
        /**
         * Get all the persons in the persons friend list.
         * @return    friends of this person
         */
        public Person [] getFriends(){
    	Friend f = friends.firstFriend;
    	int counter = 0;
    	while (f != null){
    		counter++;
    		f = f.next;
    	}
    	Person[] friendArray = new Person[counter];
    	counter = 0;
    	while (f != null){
    		friendArray[counter] = f.person;
    		counter++;
    		f = f.next;
    	}
    	System.out.println(counter);
    	return friendArray;
    	}
     
    }
     
    class PersonList {
    	Person first, last;
    	Friend firstFriend, lastFriend;
     
    	PersonList(){
    	}
     
        /**
         * Add a new person to the list
         * @param name   name of the person
         * @param phone  phone number of the person
         * @return       true if person was added successfully.
         *               false if the person is already in the list
         */
        public boolean addPerson(String name, String phone){
    	if (personExists(name)){
    	System.out.println("Name exists");
    	return false;
    	}
    	Person p = new Person(name, phone);
    	if (first == null){
    		first = p;
    		last = p;
    		System.out.println("Person added");
    		return true;
    	}
    	last.next = p;
    	p.previous = last;
    	last = p;
    	System.out.println("Person added");
    	return true;
    	}
     
        /**
         * Remove a person from the list.
         * @param name   name of the person
         * @return       true if person was successfully removed
         *               false if the person doesn't exist.
         */
        public boolean removePerson(String name){
    	if (!personExists(name)) return false;
    	Person remove = getPerson(name);
    	if (name.equals(first.getName()) && name.equals(last.getName())) {
    		first = null;
    		last = null;
    		return true;
    	}
    	if (name.equals(first.getName())){
    	first = first.next;
    	first.previous = null;
    	}
    	else (remove.previous).next = remove.next;
     
    	if (name.equals(last.getName())){
    	last = last.previous;
    	last.next = null;
    	}
    	else (remove.next).previous = remove.previous;
     
    	removeFromFriends(name);
    	return true;
    	}
     
        /**
         * Add a person as a friend to another person
         * @param name        name of the person to gain a friend
         * @param friendName  name of the new friend
         * @return            true if successfully added person as friend
         *                    false if friendName is already a friend
         */
        public boolean addFriend(String name, String friendName){
    	if (!personExists(name) || !personExists(friendName)) return false; //MAYBE REMOVE (SEE WHAT TESTER SAYS)!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
     
    	PersonList l = getPerson(name).friends;
    	Friend f = l.firstFriend;
    	while (f != null){
    		if (f.name.equals(friendName)) return false;
    		f = f.next;
    	}
    	Friend n = new Friend(getPerson(friendName));
     
    	if (l.firstFriend == null){
    		l.firstFriend = n;
    		l.lastFriend = n;
    		return true;
    	}
     
    	l.lastFriend.next = n;
    	n.previous = l.lastFriend;
    	l.lastFriend = n;
    	return true;
    	}
     
        /**
         * Remove a friend from a person
         * @param name         name of the person to lose a friend
         * @param friendName   name of the friend to be removed
         * @return             true if successfully removd person as friend
         *                     false if friendName isn't a friend
         */
        public boolean removeFriend(String name, String friendName){
    		if (!personExists(name) || !personExists(friendName)) return false; //  !!!!!!!!!!!!!!!!!!!!!!!!!!
    		PersonList l = getPerson(name).friends;
    		Friend f = l.firstFriend;
    		while (f != null) {
    			if (f.name.equals(friendName)){			
     
     
    			if (friendName.equals(l.firstFriend.name) && friendName.equals(l.lastFriend.name)) {
    				l.firstFriend = null;
    				l.lastFriend = null;
    				return true;
    			}
    			if (f.name.equals(l.firstFriend.name)) {
    				l.firstFriend = l.firstFriend.next;
    				l.firstFriend.previous = null;
    			}
    			else (f.previous).next = f.next;
     
    			if (name.equals(lastFriend.name)) {
    				l.lastFriend = l.lastFriend.previous;
    				l.lastFriend.next = null;
    			}
    			else (f.next).previous = f.previous;
     
    			return true;
    			}
    			f = f.next;
    		}
    	return false;
    	}
     
     
        /**
         * Get the current number of persons in the list.
         * @return     number of persons
         */
        public int getSize(){
    		Person check = first;
    		int counter = 0;
    		while (check != null){
    			counter++;
    			check = check.next;
    		}
    		return counter;
    	}
     
        /**
         * Get an array of persons currently in the list.
         * @return     array of persons
         */
        public Person[] getPersons(){
    		Person check = first;
    		int counter = 0;
    		Person persons[] = new Person[getSize()];
    		while (check != null){
    			persons[counter] = check;
    			counter++;
    			check = check.next;
    		}
    		return persons;
     
    	}
     
        /**
         * Get a person.
         * @param name   name of the person to get
         * @return       person that was requested
         */
        public Person getPerson(String name){
    		Person check = first;
    		while (check != null){
    			if (check.getName().equals(name)) return check;
    			check = check.next;
    		}
    		return null;
    	}
     
    	private boolean personExists (String name) {
    	if (first == null) return false;
    	Person check = first;
    		while (check != null){
    			if (check.getName().equals(name)) return true;
    			check = check.next;
    		}
    	return false;
    	}
     
    	private void removeFromFriends(String name){
    		if (first == null) return;
    		Person check = first;
    		while (check != null){
    			PersonList l = check.friends;
    			Friend friend = l.firstFriend;
    			while (friend != null){
    				if (friend.name.equals(name)) {
    						if (name.equals(l.firstFriend.name) && name.equals(l.lastFriend.name)) {
    							l.firstFriend = null;
    							l.lastFriend = null;
    							return;
    						}
    						if (name.equals(l.firstFriend.name)){
    							l.firstFriend = l.firstFriend.next;
    							l.firstFriend.previous = null;							
    						}
    						else friend.previous.next = friend.next;
     
    						if (name.equals(l.lastFriend.name)) {
    							l.lastFriend = l.lastFriend.previous;
    							l.lastFriend.next = null;
    						}
    						else friend.next.previous = friend.previous;
     
     
    				}
    			friend = friend.next;
    			}
    		check = check.next;	
    		}
    	}
    }
     
    class Friend {
    String name; // I use name since they are unique and can be used as param to the most methods. No private requested by assignment text
    Friend next, previous;
    Person person;
     
    Friend(Person p){
    this.name = p.getName();
    this.person = p;
    }
     
    }

    Code in file Oblig1Tests.java

    import java.util.ArrayList;
    import java.util.Arrays;
     
     
    /**
     * 
     * 
     */
    class Oblig1Tests {
     
     
    	PersonList personlist;
     
    	Oblig1Tests(PersonList personlist) {
    		this.personlist = personlist;
    	}
     
     
    	/**
    	 * Tests the addPerson method in class PersonList
    	 * @param name             name of the person to add
    	 * @param phone            phone number of the person
    	 * @param expectedResult   expected return value from addPerson
    	 * @throws Exception       if the return value from addPerson does not 
    	 *                         equal the expected.
    	 */
    	void addPersonTest(String name, String phone, boolean expectedResult) 
    	throws Exception {
     
    		if (personlist.addPerson(name, phone) != expectedResult) {
     
    			if (expectedResult)
    				throw new Exception("addPerson returned false when adding person \"" 
    						+ name + "\" even though the person doesn't exist in the list");
    			else
    				throw new Exception("addPerson returned true when adding person \"" 
    						+ name + "\" even though the person exists in the list");
    		}
    	}
     
    	/**
    	 * Tests the removePerson method in class PersonList
    	 * @param name              name of the person to be removed
    	 * @param expectedResult    expected return value from removePerson
    	 * @throws Exception        if the return value from removePerson does not
    	 *                          equal the expected
    	 */
    	void removePersonTest(String name, boolean expectedResult) throws Exception {
     
    		if (personlist.removePerson(name) != expectedResult) {
     
    			if (expectedResult)
    				throw new Exception("removePerson returned false when removing person \"" 
    						+ name + "\" even though the person exist in the list");
    			else
    				throw new Exception("removePerson returned true when removing person \"" 
    						+ name + "\" even though the person shouldn't exists in the list");
    		}
     
     
    		// Checking that the removed person is no longer referenced in any persons friend list
    		Person [] all = personlist.getPersons();
     
    		for (Person p : all) {
    			Person [] friends = p.getFriends();
     
    			for (Person f : friends) {
    				if (name.equals(f.getName())) {
    					throw new Exception("The removed person "+name+" is still referenced in person " + p.getName() + "s friend list.");
    				}
    			}
    		}			
    	}
     
    	/**
    	 * Tests the addFriend method in class PersonList
    	 * @param name             name of the person to gain a friend
    	 * @param nameFriend       name of the friend to add
    	 * @param expectedResult   expected return value from addFriend
    	 * @throws Exception       if the return value from addFriend does not 
    	 *                         equal the expected
    	 */
    	void addFriendTest(String name, String nameFriend, boolean expectedResult) throws Exception {
     
    		if (personlist.addFriend(name, nameFriend) != expectedResult) {
     
    			if (expectedResult)
    				throw new Exception("addFriend returned false when adding friend \""
    						+nameFriend+"\" to person \"" + name + 
    				"\" even though they aren't friends");
    			else
    				throw new Exception("addFriend returned true when adding friend \""
    						+nameFriend+"\" to person \"" + name + 
    				"\" even though they are already friends");
    		}
    	}
     
     
    	/**
    	 * Tests the removeFriend method in class PersonList.
    	 * @param name             name of the person to lose a friend
    	 * @param friendName       name of the friend to remove
    	 * @param expectedResult   expected return value from removeFriend
    	 * @throws Exception       if the return value does not equal the expected.
    	 */
    	void removeFriendTest(String name, String friendName, boolean expectedResult) throws Exception {
     
    		if (personlist.removeFriend(name, friendName) != expectedResult) {
     
    			if (expectedResult)
    				throw new Exception("removeFriend returned false when removing \""
    						+friendName+"\" as friend form person \"" + name +
    				"\" even though they are friends");
    			else
    				throw new Exception("removeFriend returned true when removing \""
    						+friendName+"\" as friend from person \"" + name + 
    				"\" even though they aren't friends");
    		}
    	}
     
     
    	/**
    	 * Tests the getSize in class PersonList
    	 * @param extectedSize   the expected size of the list
    	 * @throws Exception     if the size of the list is not equal the expected.
    	 */
    	void sizeTest(int extectedSize) throws Exception {
     
    		if (personlist.getSize() != extectedSize) {
    			throw new Exception("Expected size " + extectedSize + " but was "
    					+ personlist.getSize());
    		}
    	}
     
    	/**
    	 * Tests that the persons returned by getPersons() in PersonList correspond
    	 * to the expected names in the variable sized array taken as argument. 
    	 * @param names        the expected names in the list
    	 * @throws Exception   if a person in the expected array is not found in 
    	 *                     the returned array, or vice versa.
    	 */
    	void getPersonsTest(String ... names) throws Exception {
     
    		Person[] persons = personlist.getPersons();
     
    		if (persons == null) {
    			throw new NullPointerException("getPersons() should never return null. Return an empty array instead.");
    		}
     
    		ArrayList<Person> personList = new ArrayList<Person>(Arrays.asList(persons));
     
    		for (String name : names) {
     
    			boolean found = false;
     
    			for (Person p : persons) {
    				if (name.equals(p.getName())) {
    					personList.remove(p);
    					found = true;
    					break;
    				}
    			}
     
    			if (!found) {
    				throw new Exception("Person \"" + name + 
    				"\" was not found in the list of persons.");
    			}
    		}
     
    		// Test if there are names in the list that does not exist in the expected
    		if (personList.size() > 0) {
     
    			String nameList = "";
     
    			for (Person p : personList) {
    				nameList += "\"" + p.getName() + "\" ";
    			}
     
    			throw new Exception("The following persons should not exist in the person list:" + nameList);
    		}
    	}
     
    	/**
    	 * Tests that the persons returned by getPersons() in PersonList correspond
    	 * to the expected names in the variable sized array taken as argument. 
    	 * @param names        the expected names in the list
    	 * @throws Exception   if a person in the expected array is not found in 
    	 *                     the returned array, or vice versa.
    	 */
    	void getFriendsTest(String name, String ... friendNames) throws Exception {
     
    		Person person = personlist.getPerson(name);
     
    		if (person == null)
    			throw new Exception("Person " + name + " should exist, but was not found in the list");
     
    		Person [] friendslist = person.getFriends();
     
    		if (friendslist == null) {
    			throw new NullPointerException("getFriends() should never return null. Return an empty array instead.");
    		}
     
    		ArrayList<Person> friendList = new ArrayList<Person>(Arrays.asList(friendslist));
     
    		for (String friendName : friendNames) {
     
    			boolean found = false;
     
    			for (Person p : friendList) {
    				if (friendName.equals(p.getName())) {
    					friendList.remove(p);
    					found = true;
    					break;
    				}
    			}
     
    			if (!found) {
    				throw new Exception("Person \"" + friendName + 
    				"\" was not found in the list of friends for person " + name);
    			}
    		}
     
    		// Test if there are names in the list that does not exist in the expected
    		if (friendList.size() > 0) {
     
    			String nameList = "";
     
    			for (Person p : friendList) {
    				nameList += "\"" + p.getName() + "\" ";
    			}
     
    			throw new Exception("The following persons should not exist in the friend list:" + nameList);
    		}
    	}
     
     
     
    	/**
    	 * Runs some tests on the PersonList class
    	 * If the PersonList does not behave the expected way, an exception is thrown
    	 * The boolean value sent to the methods are the expected return values.
    	 * @throws Exception   if any of the tests fail
    	 */
    	void runTests() throws Exception {
     
    		addPersonTest("Are",        "9293847", true);
    		addPersonTest("Christian",  "3547257", true);
    		addPersonTest("Erlend",     "4568382", true);
    		addPersonTest("Espen",      "7567575", true);
    		addPersonTest("Jose",       "8765343", true);
    		addPersonTest("Simen",      "2562344", true);
    		addPersonTest("Stian",      "4563613", true);
     
    		// These are the expected persons in the person list
    		getPersonsTest("Are", "Christian", "Erlend", "Espen", "Jose", "Simen", "Stian");
     
    		// Here size should be 7
    		sizeTest(7);
     
    		// Test already added
    		addPersonTest("Are",        "9293847", false);
    		addPersonTest("Espen",      "7567575", false);
     
    		// Here size should be 7
    		sizeTest(7);
     
    		// Add three friends
    		addFriendTest("Erlend", "Stian", true);
    		addFriendTest("Erlend", "Christian", true);
    		addFriendTest("Erlend", "Simen", true);
     
    		// Test removing person
    		removePersonTest("Espen", true);
     
    				// Test removing non-existing person
    		removePersonTest("nonexistingperson", false);
     
    		// Test removing a person that has already been removed
    		removePersonTest("Espen", false);
     
    		// Here size should be 6
    		sizeTest(6);
     
    		// Add three friends
    		addFriendTest("Erlend", "Stian", true);
    		addFriendTest("Erlend", "Christian", true);
    		addFriendTest("Erlend", "Simen", true);
     
    		// Already friends
    		addFriendTest("Erlend", "Simen", false);
     
    		// Tests that the person (first argument) has the friends he should have
    		getFriendsTest("Erlend", new String[] {"Stian", "Christian", "Simen"});
     
    		// Remove two friends
    		removeFriendTest("Erlend", "Simen", true);
    		removeFriendTest("Erlend", "Christian", true);
     
    		// They are no longer friends, so should return false
    		removeFriendTest("Erlend", "Simen", false);
     
    		// Should work to add as friend again
    		addFriendTest("Erlend", "Simen", true);
     
    		// Never were friends in the first place
    		removeFriendTest("Espen", "Stian", false);
     
    		// Tests that the person (first argument) has the friends he should have
    		getFriendsTest("Erlend", new String[] {"Stian", "Simen"});
     
    		// Remove person Stian, he should no longer be in Erlends friend list
    		removePersonTest("Stian", true);
     
    		// Adding more persons
    		addPersonTest("Ruben",      "4563613", true);
    		addPersonTest("Lars",      "4563613", true);
     
    		// These are the expected persons in the person list
    		getPersonsTest("Are", "Christian", "Erlend", "Jose", "Simen", "Ruben", "Lars");
     
    		System.err.println("All tests run with no errors.");
    	}
     
    }


    Compile with: javac Oblig1.java Oblig1Tests.java
    Run with: java Oblig1 test.

    Output:

    Person added
    Person added
    Person added
    Person added
    Person added
    Person added
    Name exists
    Name exists
    Exception...java.lang.NullPointerException
    at PersonList.addFriend(Oblig1.java:166)
    error in testfile: line 85, 268...

    I do not understand what the problem is... whether or not firstFriend is null or not shouldn't matter...


    I know my code is totally messed up. I misunderstood the assignment thinking I could use the inbuilt LinkedList at first, this thing i just splashed together in a few hours...

    Any help would be appreciated!
    Last edited by westandeast; February 6th, 2011 at 09:13 AM.


Similar Threads

  1. Exception in thread "main" java.lang.NullPointerException
    By MryJaho in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 4th, 2011, 05:36 PM
  2. Replies: 16
    Last Post: August 27th, 2010, 03:30 PM
  3. Replies: 2
    Last Post: March 26th, 2010, 11:22 AM
  4. Please help! Exception in thread "main" java.lang.NullPointerException
    By Arutha2321 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 18th, 2009, 02:25 AM