1

In an array of strings 'a' having 'n' strings i have to select the Palin Pairs from the given strings .for ex for input 3 bba abb abb Output=2 what m i doing wrong

import java.util.*;
class Test {
  public static void main(String args[]) {
    int i,j,k=0;
    Scanner h=new Scanner(System.in);
    int n=h.nextInt();
    String a[]=new String[n];

    for(i=0;i<n;i++) {
      if(a[i]!="") {
        String rev = (new StringBuffer(a[i])).reverse().toString();
        for(j=i+1;j<n;j++) {
          if(rev.equals(a[j])) {
            k++;
            a[j]="";
          }
        }
      }
    }

    h.close();
  }
}
C1pher
  • 1,933
  • 6
  • 33
  • 52

2 Answers2

4

You're creating a String array, but never initializing its members.

The default values of the members are null.

Hence, when you call new StringBuffer(a[i]), you're passing a null value.

You could avoid this by:

  • Filling the array with something.
  • Checking for null in addition to your existing check for empty string.

By the way, you're attempting to check for empty string with the equality operator !=. This will check that the references are different, not that the String objects to which they point contain different strings. You'll want to check instead with either:

  (null != a[i]) && ! a[i].isEmpty()

or

  ! "".equals( a[i] )

or, if you're using Google's guava library:

  ! Strings.isNullOrEmpty( a[i] )
Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
  • thanks that solved it n i m getting output :-),just one more question why cant i check empty string with equality operator – Shivangi Awasthi Jul 24 '15 at 20:22
  • @ShivangiAwasthi - You caught me mid-edit. That's included above now. The equality operator checks that the *references* are equal. You can see more detail about that in this question: http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Andy Thomas Jul 24 '15 at 20:25
  • @Andy Thomas A better way to check whether a[I] is empty is "a[i].isEmpty()" – FredK Jul 24 '15 at 21:13
  • @FredK - You're right, that's higher-level than the explicit length check -- which is how `isEmpty()` is implemented. I'll add it above. The `"".equals()` check works whether the reference is null or not. There's also guava's Strings.isNullOrEmpty(). – Andy Thomas Jul 24 '15 at 21:20
1

Most likely you are expecting to read the words from the console which you are not doing. I suggest you use Scanner.nextLine().

int n=h.nextInt();
h.nextLine(); // discard the rest of the line.
String a[]=new String[n];

for(int i = 0; i < n; i++) {
   // read a word.
   a[i] = h.nextLine();
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • Or with `Scanner.next()`, if the words are on the same line. You're right, if the count is coming from stdin, likely the data is as well. – Andy Thomas Jul 24 '15 at 21:31