用于识别给定行是否为注释的Java程序

时间:2018-01-18 07:44:41

标签: java

我正在创建一个java程序来测试给定的字符串是否是注释,到目前为止这是我的代码:

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");
         }
         }
     }

我在这行代码上遇到错误:

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

错误说:java.lang.NullPointerException

有关为何发生这种情况的任何解释?

1 个答案:

答案 0 :(得分: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.