-1

I have a Java code that should print nothing if no-element string is passed.Currently,my method is passing all tests but the one with no-element string.It gives me error.Code is below.Any suggestions are welcome.

public static void printLetters(String text)
{

System.out.print(text.charAt(0));

for(int i=1;i<text.length();i++)
{
    System.out.print("-" + text.charAt(i));
}

System.out.println();
}

4 Answers 4

1

My guess is your exception pops up on your line

System.out.print(text.charAt(0));

If you pass an empty string the code will try to access a char at 0. In the empty string there is no 0th char.

A check like this might suit you:

public static void printLetters(String text)
{
    if (text != null && text.length() != 0)
    {
        System.out.print(text.charAt(0));

        for(int i=1;i<text.length();i++)
        {
            System.out.print("-" + text.charAt(i));
        }
    }
    System.out.println();
}
3
  • 2
    if(text.length()!=0) can be replaced with if (!text.isEmpty()) Commented Oct 23, 2013 at 22:52
  • I don't think it will make a huge difference performance wise, but you are right to say that they reach equivalent boolean values. Commented Oct 23, 2013 at 22:59
  • Yes, performance will be similar but it would be easier to read and maintain such code. Commented Oct 23, 2013 at 23:32
1

It should be giving you giving you NullPointerException if you pass null because you are de-referencing text before checking if it is null or not and de-referencing null results in NPE.

if(text != null){
return;
}

For empty String test you can do the following

if(text.isEmpty()){
System.out.println(text);
}
0

You can simply add an if statement to check if the text variable is null, if so return.

Also you can remove the first System.out.print(text.charAt(0)); and just change so the for loop starts at i = 0

public static void printLetters(String text)
{
    if (text == null)
    {
        return;
    }

    for(int i = 0; i < text.length(); i++)
    {
        System.out.print(text.charAt(i) + ",");
    }

    System.out.println();
}
0
0

The reason why you have this problem is because if you have a string which has a null pointer the charAt(0) will automatically throw a NullPointerException. Try to evaluate first if the string has null pointet, if it's not then you can go ahead and use charAt(0) and the other operations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.