0

I am getting a null pointer exception when I call my method to create a new String copy of the passed argument. This method is called from my main.

Why am I getting this error and how do I fix it so it's not pointing to null?

It says the error is happening on this line :front.data = original.charAt(i);

and if I change the size to -1 it gives the error on this line back.next = newNode;

Main (relevant part of method):

public class TestLString {
  /** Main method */
   public static void main(String[] args) {

      String str1 = "Hello, my name is Alphose!";
      LString lstr1 = new LString(str1);

EDIT: This seemed to work!

   public LString(String original){
  size = 0;
  for(int i = 0; i< original.length(); i++){
     if(original.length() == 0){                              ///changed
        front = new Node();
        front.data = original.charAt(i);
        front.next = back;
        size++;
     } else{
           Node newNode = new Node();
           newNode.data = original.charAt(i);
           Node back = new Node();
           back.next = newNode;
           newNode.next = null;
           back = newNode;
       }
  }
  } 

my initialized data field(sorry about that). Let me know if I can add anything else.

public class LString{


   private Node front = null;  //first val in list
   private Node back;   //last val in list
   private int size = 0;
   private int i;
   private int offset;

   public LString(){
      //construct empty list
      Node LString = new Node();
      front = null;

   }
AOE
  • 109
  • 2
  • 7
  • 14

2 Answers2

2

Where you have

if (front == null) { front.data = ...; }

That definitely won't work. If front is null, then you can't assign a value to its data member.

2

EDIT

Alternate theory:

You need to initialize front before you use it:

front = new Node();
front.data = original.charAt(i);
front.next = back;
size++;

Original Theory

I'm guessing that instead of

if(front == null){

you mean

if(front != null){

because if front is null, you can't access its data (front.data = ...).

Flight Odyssey
  • 2,267
  • 18
  • 25