Problem: it print "null" in front of every line

for example
input
this is sparta

output
nullhistay isay partasay

import java.util.*;


public class PigLatin
{
  
  String[] piggieLatin;
  String[] sentence;
  public PigLatin(String[] random)
  {
    sentence = random;
    piggieLatin = new String[sentence.length];
  }

  //repalce everything beside a~z with space
  public String punctuationFree(String abc)
  {
      return abc.replaceAll("[^a-z]", " "); 
  }
  
  

  //read a string, check if the first letter is vowl, and then translate the text.
  public String piggie (String t)
  {
    if (t.charAt(0) == 'a' || t.charAt(0) == 'e' || t.charAt(0) == 'i' || t.charAt(0) == 'o' || t.charAt(0) == 'u')
      return t + "ay";
    else 
      return t.substring(1) + t.charAt(0) + "ay";
  }
  

  
  String result;
  StringTokenizer pL;
  String[] temp;

  //lowercase all line, remove punctuation, use tokenizer separate word by word, translate the text, put them back together
  public void pigAll() 
  {
    for (int k = 0; k < sentence.length; k++)
    {
      if(sentence[k] == null){continue;}
      sentence[k] = sentence[k].toLowerCase();
      sentence[k] = punctuationFree(sentence[k]);
    pL = new StringTokenizer(sentence[k]);
 
    while (pL.hasMoreTokens()) 
    {
      String temp = pL.nextToken();
      temp = piggie(temp);
      piggieLatin[k] += temp + " ";
    }  
    }
  }
  
  //print the translation.
  public void pigReport()
  {
    for (int j = 0; j<piggieLatin.length; j++)
    {
      if(piggieLatin[j] == null){continue;}
      System.out.println(piggieLatin[j]); 
    }
  }
}

Dear keiteqq,

Actual problem lies in your

public void pigAll(){
  .......
}

method and line is following

piggieLatin[k] += temp + " ";

As you have used Short Hand operator += it will append piggieLatin's initialised value which is null(Variable piggieLatin will be initialized to null in construcor)

So, for solution you can do like this,

public void pigAll() {
                /**
                  * Initialized piggieLatin's first element to blank.
                  */
		piggieLatin[0] = "";
		for (int k = 0; k < sentence.length; k++) {
			if (sentence[k] == null) {
				continue;
			}
			sentence[k] = sentence[k].toLowerCase();
			sentence[k] = punctuationFree(sentence[k]);
			pL = new StringTokenizer(sentence[k]);

			while (pL.hasMoreTokens()) {
				String temp = pL.nextToken();
				temp = piggie(temp);
				piggieLatin[k] += temp + " ";
			}
		}
	}

Hope this will help you.

:icon_smile:

But

piggieLatin[0] = "";

only solve the null problem for first line

I put that code inside the for lope, and change it to k. So it solve each line

piggieLatin[k] = "";

But thanks for the hint!!

This article has been dead for over six months. Start a new discussion instead.