11 Replies - 5315 Views - Last Post: 05 July 2011 - 07:41 PM Rate Topic: -----

#1 kamran619  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 74
  • Joined: 05-July 11

Null Pointer Exception? Really?

Posted 05 July 2011 - 06:40 PM

Hey everyone I am new to this forum, this is my first thread so please go easy on me. I am doing a couple of exercises in this java book I bought trying to prepare for my Placement Test in August. I have to make a split function similiar to the one in the String class, except this one has to include the delimiter in the parsed String.

Ex:
String k = "abcd#e";
String splitted[] = k.split("#");
splitted[0] would be abcd
splitted[1] would be #
splitted[2] would be e

This is what I have so far but I keep getting a null pointer exception where it is starred..

import java.util.Scanner;
public class StringSplit {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("Enter a string to split");
		Scanner UI = new Scanner(System.in);
		String word = UI.next();
		System.out.println("Enter a regex to use:");
		String delim = UI.next();
		String[] splitWord = split(word, delim);

	}

	private static String[] split(String word, String delim) {
		StringBuilder[] splitString;
		char[] delimSymbols;
		int counter = 0;
		//if there is more than one delim
		if (delim.charAt(0) == '['){
		   delimSymbols = new char[delim.length() - 2];
		   for (int i = 1; i < delimSymbols.length - 1; i++){
			   delimSymbols[i-1] = delim.charAt(i);
		   }
		   //there is only one delim
		}else{
			delimSymbols = new char[1];
			delimSymbols[0] = delim.charAt(0);
		}
		//check how many delim symbols there are to instantiate the array properly
		for (int i = 0; i < delimSymbols.length; i++){
			for (int j = 0; j < word.length(); j++){
				if (word.charAt(j) == delimSymbols[i]){
					counter++;
				}
			}
		}
                //include the # in the counter 
		counter *= 2;
		counter++;
		//make array with proper length
		splitString = new StringBuilder[counter];
		//loop through main string and split
		for (int i = 0; i < delimSymbols.length;){
			for (int j = 0; j < word.length(); j++){
				if (word.charAt(j) != delimSymbols[i]){
					//ERROR HERE **** NULL POINTER EXCEPTION
                                   splitString[i].append(word.charAt(j));
				}else if(word.charAt(j) == delimSymbols[i]){
					if (j != 0){
						if (delimSymbols.length > 1){
						i++;
					}
					}
					splitString[i].append(word.charAt(j));
				}
			}
		}
		
		//fill the array
		String[] completed = new String[splitString.length];
		System.arraycopy(splitString, 0, completed, 0, completed.length);
		return completed;
	}

}



Is This A Good Question/Topic? 0
  • +

Replies To: Null Pointer Exception? Really?

#2 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 10364
  • View blog
  • Posts: 38,362
  • Joined: 27-December 08

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 06:41 PM

Moved to Java. Please reserve the Java Programmers forum for topical, non-help related discussion.

Post your stack trace.
Was This Post Helpful? 0
  • +
  • -

#3 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 06:47 PM

View Postkamran619, on 05 July 2011 - 09:40 PM, said:

Ex:
String k = "abcd#e";
String splitted[] = k.split("#");
splitted[0] would be abcd
splitted[1] would be #
splitted[2] would be e

The split() method does not return the seperator so it will be
splitted[0] would be abcd
splitted[1] would be e

And nothing stops you from putting multiple delemiters so

String k = "ab,cd#e";
String splitted[] = k.split("#,");
splitted[0] would be ab
splitted[1] would be cd
splitted[2] would be e

your are doing a lot of work for nothing
and if you really want the list of the different delimiters, the String class has a toCharArray() method

This post has been edited by pbl: 05 July 2011 - 06:51 PM

Was This Post Helpful? 1
  • +
  • -

#4 kamran619  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 74
  • Joined: 05-July 11

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 06:53 PM

View Postpbl, on 05 July 2011 - 06:47 PM, said:

View Postkamran619, on 05 July 2011 - 09:40 PM, said:

Ex:
String k = "abcd#e";
String splitted[] = k.split("#");
splitted[0] would be abcd
splitted[1] would be #
splitted[2] would be e

The split() method does not return the seperator so it will be
splitted[0] would be abcd
splitted[1] would be e

And nothing stops you from putting multiple delemiters so

String k = "ab,cd#e";
String splitted[] = k.split("#,");
splitted[0] would be ab
splitted[1] would be cd
splitted[2] would be e

your are doing a lot of work for nothing
and if you really want the list of the different delimiters, the String class has a toCharArray() method


I think my explanation was a bit confusing. I have to MAKE a NEW split method that splits the String and INCLUDES the delimiter as well..I have it so there can be multiple delimiters in the code as well. I am getting a null pointer exception though for some odd reason.

Here is the trace:

Exception in thread "main" java.lang.NullPointerException
at StringSplit.split(StringSplit.java:48)
at StringSplit.main(StringSplit.java:13)
Was This Post Helpful? 0
  • +
  • -

#5 MATTtheSEAHAWK  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 137
  • View blog
  • Posts: 782
  • Joined: 11-September 10

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 06:55 PM

Well I can think of what I would do for this. I would create a string[3] named splits. Then I would loop through the string. And I would declare one more variable which would be a bool named foundDelim. Then in the for loop I would make an if then to check if the current char is the delimiter and if it is then make splits[1] equal to the delimiter and set foundDelimiter to true and if not then add the current char to splits[0]. But at the beginning of the loop I would make an if then to see if foundDelimiter is true and if it is then add the current char to splits[2]. That's basically how I would do it. Yours seems a little long...

Also try stringSplit = word.charAt(j); instead of append. Because you're trying to append a char to a char which won't work.

But anyways yours just seems way to complicated and I don't even know if what I said above about the stringBuilder will work. Try what I said int the first paragraph or something really similar.
Was This Post Helpful? 0
  • +
  • -

#6 kamran619  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 74
  • Joined: 05-July 11

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:01 PM

View PostMATTtheSEAHAWK, on 05 July 2011 - 06:55 PM, said:

Well I can think of what I would do for this. I would create a string[3] named splits. Then I would loop through the string. And I would declare one more variable which would be a bool named foundDelim. Then in the for loop I would make an if then to check if the current char is the delimiter and if it is then make splits[1] equal to the delimiter and set foundDelimiter to true and if not then add the current char to splits[0]. But at the beginning of the loop I would make an if then to see if foundDelimiter is true and if it is then add the current char to splits[2]. That's basically how I would do it. Yours seems a little long...

Also try stringSplit = word.charAt(j); instead of append. Because you're trying to append a char to a char which won't work.

But anyways yours just seems way to complicated and I don't even know if what I said above about the stringBuilder will work. Try what I said int the first paragraph or something really similar.


That's not correct though. Let's say the string I give it is "#123#" and the delimiter is also a "#". The first element int the array should be #, then 123, then #. Also, the stringSplit is an array of the Stringbuilder data type and the only way I can add to the element is by the insert or append method at the proper index.
Was This Post Helpful? 0
  • +
  • -

#7 MATTtheSEAHAWK  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 137
  • View blog
  • Posts: 782
  • Joined: 11-September 10

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:08 PM

Ok well then what me change what I said. This works in my mind: Modify it to make an ArrayList of type string. Then a string currentString. Both of those are outside of the loop. Every time you don't see a delimiter then add that char to the currentString. If you see a delimiter then add the currentString to the ArrayList and then add the delimiter. After that just reset currentString to equal "". I think that should work but give it a try.

Also sorry about my middle suggestion I didn't read close enough.
Was This Post Helpful? 1
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:12 PM

So use an ArrayList<StringBuilder> you won't have to count the number of elements that your array will have

When you encounter a delimiter:
arrayList.add(new StringBuilder(delimiterFound));
StringBuilder b = new StringBuilder();
arrayList.add(B);
append to b until next delimiter found
Was This Post Helpful? 1
  • +
  • -

#9 kamran619  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 74
  • Joined: 05-July 11

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:14 PM

View PostMATTtheSEAHAWK, on 05 July 2011 - 07:08 PM, said:

Ok well then what me change what I said. This works in my mind: Modify it to make an ArrayList of type string. Then a string currentString. Both of those are outside of the loop. Every time you don't see a delimiter then add that char to the currentString. If you see a delimiter then add the currentString to the ArrayList and then add the delimiter. After that just reset currentString to equal "". I think that should work but give it a try.

Also sorry about my middle suggestion I didn't read close enough.


Thanks! That sounds similar to what I am doing here except I am not using an ArrayList. I am putting everything into the i'th element of splitString until I hit a delimiter, then I am putting the delimiter in the next spot after I increment i. The way I have it should work, except for this error I am getting. I am trying to use only what I have learned so far. I haven't covered Lists or any other advanced data structure yet. When I debug this in eclipse, it shows me my StringBuilder object is initialized will all null values. I think the error happens because I am appending a character to null. Any ideas of how to get around this?
Was This Post Helpful? 0
  • +
  • -

#10 MATTtheSEAHAWK  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 137
  • View blog
  • Posts: 782
  • Joined: 11-September 10

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:23 PM

If you did an ArrayList<StringBuilder> you wouldn't have to count them and it would take some off of your load. Also and yes I think the error is happening because all of the string builders in your splitString are null. Like me and pbl said, if you did an ArrayList<StringBuilder> then you could instantiate a new StringBuilder every time through the loop. I hope this helps :)

EDIT: Crap pbl I accidentally hit the negative rep button. Sorry I meant to hit the positive :(. Plus repped you up higher to fix it.

This post has been edited by MATTtheSEAHAWK: 05 July 2011 - 07:24 PM

Was This Post Helpful? 2
  • +
  • -

#11 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8324
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:36 PM

Something like that should work

	public String[] split(String str, String delim) {
		
		ArrayList<StringBuilder> al = new ArrayList<StringBuilder>();
		char[] orig = str.toCharArray();
		char[] split = delim.toCharArray();
		
		// int a StringBuilder
		StringBuilder builder = new StringBuilder();
		// scan all characters in the string
		for(int i = 0; i < orig.length; ++i) {
			int j;
			// search if it is a delimiter
			for(j = 0; j < split.length; ++j) {
				// if it is a delimiter
				if(orig[i] == split[j]) {
					// if the builder has element it it
					if(builder.length() != 0) {
						// push it into the arrayList
						al.add(builder);
						// and prepare a new one in case we haven't finish to parse the String
						builder = new StringBuilder();
					}
					// add the delimiter 
					al.add(new StringBuilder(orig[i]));
					// done
					break;
				}
			}
			// if no delimter were found append the character from the String
			if(j == split.length)
				builder.append(orig[i]);
		}
		// if we didn't finish with a delimiter their will be something on the builder
		if(builder.length() > 0)
			al.add(builder);
		// convert our ArrayList of StringBuilder into an array of String
		String[] result = new String[al.size()];
		for(int i = 0; i < result.length; ++i)
			result[i] = al.get(i).toString();
		return result;
	}



View PostMATTtheSEAHAWK, on 05 July 2011 - 10:23 PM, said:

EDIT: Crap pbl I accidentally hit the negative rep button. Sorry I meant to hit the positive :(. Plus repped you up higher to fix it.

Don't worry, you will have other occasions :)
Was This Post Helpful? 3
  • +
  • -

#12 kamran619  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 74
  • Joined: 05-July 11

Re: Null Pointer Exception? Really?

Posted 05 July 2011 - 07:41 PM

View Postpbl, on 05 July 2011 - 07:36 PM, said:

Something like that should work

	public String[] split(String str, String delim) {
		
		ArrayList<StringBuilder> al = new ArrayList<StringBuilder>();
		char[] orig = str.toCharArray();
		char[] split = delim.toCharArray();
		
		// int a StringBuilder
		StringBuilder builder = new StringBuilder();
		// scan all characters in the string
		for(int i = 0; i < orig.length; ++i) {
			int j;
			// search if it is a delimiter
			for(j = 0; j < split.length; ++j) {
				// if it is a delimiter
				if(orig[i] == split[j]) {
					// if the builder has element it it
					if(builder.length() != 0) {
						// push it into the arrayList
						al.add(builder);
						// and prepare a new one in case we haven't finish to parse the String
						builder = new StringBuilder();
					}
					// add the delimiter 
					al.add(new StringBuilder(orig[i]));
					// done
					break;
				}
			}
			// if no delimter were found append the character from the String
			if(j == split.length)
				builder.append(orig[i]);
		}
		// if we didn't finish with a delimiter their will be something on the builder
		if(builder.length() > 0)
			al.add(builder);
		// convert our ArrayList of StringBuilder into an array of String
		String[] result = new String[al.size()];
		for(int i = 0; i < result.length; ++i)
			result[i] = al.get(i).toString();
		return result;
	}



View PostMATTtheSEAHAWK, on 05 July 2011 - 10:23 PM, said:

EDIT: Crap pbl I accidentally hit the negative rep button. Sorry I meant to hit the positive :(. Plus repped you up higher to fix it.

Don't worry, you will have other occasions :)


I actually just figured out how to do it without using an ArrayList. I repped both of you! The suggestion to use a StringBuilder instead of a StringBuilder[] fixed my problem. Thanks for all your help and quick replies!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1