-3

I'm creating a java program to test if the given string is a comment or not and here's my code so far:

public class comment {
public static void main(String args[]){
    String[] com = new String[50];
    Scanner scan = new Scanner(System.in);
    int i = 2 ,a=0;
    System.out.println("Enter comment");

   com[i] = scan.nextLine();

     if(com[0].equals("/")){
         if(com[1].equals("/")){
             System.out.println("comment");
         }
         else if (com[1].equals("*")){
         for(i=2;i<=50; i++){
             if(com[1].equals("*") && com[i+1].equals("/") ){
                 System.out.println("comment");
                 a=1;
                 break;
             }
             else{
                 continue;}}
         if(a==0){System.out.println("not");}
             }
         else{System.out.println("not");
         }
         }
      else{System.out.println("not");
         }
         }
     }

I'm getting an error on this line of code:

 if(com[0].equals("/"))

Error says: java.lang.NullPointerException

Any explanation on why is this occuring ?

Bry
  • 25
  • 8
  • `com[0]` must be null, which makes sense, since you only assign value to `com[2]` – Eran Jan 18 '18 at 07:45
  • also: you can't decide this based on a single line. /**text*/ here text is a comment, but if you only check the single line, you would never know. – Stultuske Jan 18 '18 at 07:47
  • To avoid getting NullPointerException when comparing you can do: if("/".equals(com[0])), but that doesn't change the fact that you initizalized a String array with 50 positions, stored something in com[2] but nothing in com[0] – tec Jan 18 '18 at 07:54

1 Answers1

0
String[] com = new String[50]; //You are defining an array of strings.
...
int i = 2 ,a = 0; //You are defining i as 2
...
com[i] = scan.nextLine();// You are setting com[2] with the next line

//com[0] is still null and pointing to nothing

if(com[0].equals("/")) //Hence null.equals("") will throw a NullPointerException. 
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78
  • It worked but once I type strings with comment character it always displays not. – Bry Jan 18 '18 at 07:57