Write a method that searchs for a specific string within another string; the method must return true if the former exists in the latter string. For example: isSubString("cat", "The cat in the hat.") is true, but isSubString("bat", "The cat in the hat.") is false. Also, verify that the boundry conditions are also met. Also, verify that the boundry conditions are also met: isSubString("The", "The cat in the hat.") is true 
isSubString("hat.", "The cat in the hat.") is true 
以上是要求,下面是我的程序:
class StrSearch
{       private String one;
        private String another;
        public StrSearch(String another,String one)
        {
         this.another=another;
         this.one=one;
        }
        int n=another.length();
int max=one.length()-another.length();
public boolean test()
{
            //int j=0;
for(int i=0;i<max;i++)
{
if(another.charAt(0)==one.charAt(i))
{
int j=1;
while(n--!=0)
                                {
                                       if(another.charAt(j++)==one.charAt(i+(j++)));
                                }
                                 return true;     
}
else continue;
}
return false;
}
}
public class Txt 
{
public static void main(String [] args)
{
        StrSearch str=new StrSearch("cat","The cat in the hat");
if(str.test())
{
                System.out.println("true");
                }
                else 
                {
                 System.out.println("false");
                }
}
}
运行的时候总是说空指针异常,在学习的过程中经常遇到这种问题,请问这是怎么回事啊?
谢谢阿

解决方案 »

  1.   

    int n=another.length();
    int max=one.length()-another.length();
    把这两句放到test()方法中去。
      

  2.   

    int n=another.length();
    int max=one.length()-another.length();
    这两句不在任何的方法里面,他会被当作构造函数的一部分首先执行
    这两句的执行会在this.another=another;  this.one=one;  之前
    所以another,one都为null就会有NullPointerException了
      

  3.   

    先看看java编程思想的初始化吧对象在初始化的时候首先初始化成员变量,然后是构造函数你的两个成员变量都没有初始化,就直接int max=one.length()-another.length();肯定是空指针呀
      

  4.   

    本人是一名JAVA爱好者!先建JAVA群一个,希望能结识喜欢JAVA的朋友一起学习探讨!!!群里面有JAVA老师一名(电子科大博士),还有众多技术员,欢迎各位的加入!!!!!!群号:10549859        本人QQ:21789690