【Debug】

握草 2017-10-30 09:06:56
package math011;

public class Math011 {
public static void main(String[] args) {
int maxCycleLength=0;
for(int i=2; i<=1000; ++i) {
double tmpDecimal=(double)1/i;
String tmpStr=String.valueOf(tmpDecimal).substring(0,500);
int tmpCycleLength=getMaxCycleLength(tmpStr);
if(tmpCycleLength>maxCycleLength) {
maxCycleLength=tmpCycleLength;
}
}
System.out.println(maxCycleLength);
}

public static int getMaxCycleLength(String str) {
int maxCycleLength = 0;
int tmpCycleLength = 0;
for (int i = 1; i < str.length(); ++i) {
for (int j = 0; j < str.length() - i; ++j) {
if (str.charAt(j) == str.charAt(i + j))
tmpCycleLength++;
// As follow, tmpCycle is always change, and pass the value to the maxCycle,
// finally the value will be fixed.
else
tmpCycleLength = 0;
if (tmpCycleLength > maxCycleLength) {
maxCycleLength = tmpCycleLength;

}

}
}
if (maxCycleLength > 0)
return maxCycleLength;
return -1;

}


}


如上,要求找出1/2, 1/3, 1/4。。。1/1000 之中的循环节最多的一个数
为什么这样写在主方法中会导致:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 500
at java.lang.String.substring(String.java:1963)
at math011.Math011.main(Math011.java:8)

这样的错误??
...全文
381 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
握草 2017-10-31
  • 打赏
  • 举报
回复
哦对!! 我怎么忘了这个,1/2=0.5~ 但是如果要实现这个方法,应该怎么改进呢??
pheonix0992 2017-10-31
  • 打赏
  • 举报
回复

IndexOutOfBoundsException - if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex.
你把tmpDecimal转化为String类型,字符串没有500的长度,使用subString就报错了。
握草 2017-10-31
  • 打赏
  • 举报
回复
引用 5 楼 l359122505 的回复:
[quote=引用 3 楼 qq_40778536 的回复:] 哦对!! 我怎么忘了这个,1/2=0.5~ 但是如果要实现这个方法,应该怎么改进呢??
不用substring就行了。如果想保留小数点后500位的话可以使用BigDecimal[/quote]BigInteger tmpDe=new BigInteger((long)tmpDecimal); 这样吗??
繁华终归落尽 2017-10-31
  • 打赏
  • 举报
回复
引用 3 楼 qq_40778536 的回复:
哦对!! 我怎么忘了这个,1/2=0.5~ 但是如果要实现这个方法,应该怎么改进呢??
不用substring就行了。如果想保留小数点后500位的话可以使用BigDecimal
握草 2017-10-30
  • 打赏
  • 举报
回复
谢绝水贴!文明网络环境,你我共创美好

62,626

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧