专注收集记录技术开发学习笔记、技术难点、解决方案
网站信息搜索 >> 请输入关键词:
您当前的位置: 首页 > Java Exception

为什么程序中有退出的代码java还要抛出异常呢?

发布时间:2010-06-05 12:36:38 文章来源:www.iduyao.cn 采编人员:星星草

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class FindMaxRepeatString
{
/*print the string
*the parameter explain is the declaring words,
*and the string is for printing
*/
public static void printString(String explain,String str)
{
System.out.print(explain);
System.out.println(str);
}

//the function is output integer
public static void printString(String explain,int Int)
{
System.out.print(explain);
System.out.println(Int);
}
//the main function
public static void main(String args[])
{
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
String str = null;//define a str for save the input string
String sub=null; //safe a sub string from the str
System.out.println("Input a string :");
try
{
str=buf.readLine();
}
catch(IOException e)
{
System.err.println("Input error:"+e.getMessage());
}

//print the string which you input
printString("the str you input is:",str);
  //当str=null时,退出程序
if(str==null)
System.exit(0);

int position=0; //record the start point of the sub string
int maxCount=0; //Save the max equal count
//Save the length of the sub string which is repeat max in string
int maxLen=1;
sub=str.substring(0,0);
int i=1;
try
{
// TODO: handle exception
for(int k=0;k <str.length()-1;k++) //k表示从第几位开始比较
{
for(i=1;i <=str.length()/2&&(k+i) <str.length();i++)
{
sub=str.substring(k, k+i);
System.out.println("the sub is :"+sub);
int count=0;
for(int j=i+k;sub.length() <=str.length()-j;j+=sub.length())
{
String s=str.substring(j,j+i);
System.out.println("the s is :"+s);
if(sub.compareTo(s)==0)
count++;
else
break;
}
if(maxCount <count||(count>0&&maxCount==count&&maxLen <sub.length()))
{
maxCount=count;
position=k;
System.out.println("position is :"+position);
maxLen=sub.length();
}
}
}
}
catch(NullPointerException e)
{
System.err.println("Main: Null point error:"+e.getMessage());
}
  //这句代码抛出异常
sub=str.substring(position, position+maxLen);
printString("the start of the sub in the string is:", position);
printString("the length of the sub is:", maxLen);
printString("the compare most count is:", maxCount);
printString("The sub string repeat most is:", sub);
}
}

我就是不明白为什么
我还成了这样:
if(str!=null)
  sub=str.substring(position, position+maxLen);
它还是要抛出异常,为什么呢???
另外:我用str.trim();为什么不能去掉空格呢???
还用过了str.replaceAll(" ","");
都没用啊?这又是为什么啊

------解决方法--------------------------------------------------------
判断改为  if (null == str || "".equals(str))
你可以调试跟一下程序 就会发现当回车的时候 str="" 而不是NULL 

    
友情提示:
信息收集于互联网,如果您发现错误或造成侵权,请及时通知本站更正或删除,具体联系方式见页面底部联系我们,谢谢。

其他相似内容:

热门推荐: