0
import java.util.*;
public class s22 {

    public static void main(String[] args) {
        //Your Code Here
        Scanner sb=new Scanner(System.in);
        int n=sb.nextInt();
                int i,j;
        String[] st=new String[1000];
                String[] s=new String[n];
        for(i=0;i<n;i++)
        {
            st[i]=sb.next();
        }
        
        for(j=0;j<n;j++)
                 {
                String[] m=st[i].split(" ");
                 s[i]=m[m.length-1];
                 }
                 for(i=0;i<n;i++){
                System.out.println(s[i]);}
                  
    }
}

I tried this code but shows null pointer exception after entering first value. For example if I give input as:

john is sleeping,
lisa rapper,
beautiful flower,

The output should be like:

sleeping,
rapper,
flower

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TEN
  • 1
  • 1
  • The problem comes from declaring your variables earlier than you need them. Delete the declarations of `i` and `j` from where they stand now. Then use the conventional `for (int i = 0; i < n; i++)`. Similarly for the second loop. Then your IDE or compiler will point out where your mistake is. (Another problem is declaring your array `st` larger than you need it. It should just have size `n`, the same as `s`.) – Ole V.V. Jul 10 '20 at 19:58
  • While this question may be considered a duplicate, I disagree about the choice of original question. TEN, you will very often be asking questions that have been asked before, and you can help us find the right one. When asking about code that doesn’t work as expected, paste both error message and also stack trace in case of an exception into the question. Format the stack trace as code. And inform us which code line the stack trace refers to. It will make it easier for everyone and in the end yourself. Please also indent your code properly, thanks. – Ole V.V. Jul 12 '20 at 07:47

0 Answers0