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");
}
}
}
运行的时候总是说空指针异常,在学习的过程中经常遇到这种问题,请问这是怎么回事啊?
谢谢阿
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");
}
}
}
运行的时候总是说空指针异常,在学习的过程中经常遇到这种问题,请问这是怎么回事啊?
谢谢阿
int max=one.length()-another.length();
把这两句放到test()方法中去。
int max=one.length()-another.length();
这两句不在任何的方法里面,他会被当作构造函数的一部分首先执行
这两句的执行会在this.another=another; this.one=one; 之前
所以another,one都为null就会有NullPointerException了