-1

The code is to shorten names.

When am executing in Hackerrank there is NullPointerException on temp.length() , temp.toUpperCase() , temp.substring(). Visit the question here

The First Line contains an integer N, which denotes the number of testcases.

Sample Input

3

Mohandas Karamchand Gandhi

Mervin R Sundharam

Muthu

Sample Output

M K Gandhi

M R Sundharam

Muthu

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) throws IOException {
        Scanner sc= new Scanner(System.in);
        int size= sc.nextInt();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        String ar[] =new String[size];
        for (int i= 0; i < size; i++) {
           ar[i]=br.readLine();
       }

        for(int i= 0;i<size;i++){
            String temp=" ";
            temp=ar[i];
            int pos=0;
            for (int j= 0; j < temp.length(); j++)
                if(temp.charAt(j)==' '){
                    System.out.print(temp.toUpperCase().charAt(pos)+ " ");
                    pos=j+1;
                }
            }
            System.out.println(temp.toUpperCase().charAt(pos)+temp.substring(pos+1));
        }
    }
}
Austin p.b
  • 356
  • 6
  • 11
  • The `BufferedReader`'s `readLine()` method returns `null` when the stream sends an `EOF` signal. Maybe that is what is causing the `NullPointerException`. – Titus Mar 22 '16 at 02:03
  • Your program doesn't even compile. How can it produce a NPE? – laune Mar 22 '16 at 02:03
  • You haven't included a stack trace, but if the NPE occurs at `for (int j= 0; j < temp.length(); j++)`, it will be because the file isn't as long as you think it is, so `temp` is null. You should break out of the loop once you encounter a `false` from `Scanner.nextLine()`, and in the second loop if `ar[i] == null`. And complain about the malformed input file. You should get rid of the `BufferedReader` altogether. – user207421 Mar 22 '16 at 04:10

1 Answers1

-1

Change from ar[i]=br.readLine(); to ar[i]=sc.nextLine(); in the first for loop.

Milind Gokhale
  • 563
  • 2
  • 12