我正在编写一个程序来计算:
1^1 + 2^2 + 3^3 + ... + 1000^1000 = ?
计算完成后,我希望除了最后十位数字之外,删除答案中的所有数字,并将最终十位数字打印在屏幕上。为了删除其他所有数字,我正在使用 StringBuilder.deleteCharAt()
方法,但是这给我带来了一些问题。我提供了我的代码如下:
import java.math.BigInteger;
public class problemFourtyEight {
public static void main(String [] args) {
BigInteger answer = new BigInteger(""+0);
for(int i = 0; i <= 1000; i++) {
BigInteger temp = new BigInteger(""+i);
temp = temp.pow(i);
answer = answer.add(temp);
}
System.out.println(answer.toString().length());
StringBuilder sb = new StringBuilder((answer.toString()));
for(int k = 0; k <= (answer.toString().length() - 10); k++) {
sb.deleteCharAt(k); //Line 13 is here.
}
String finalAnswer = sb.toString();
System.out.println(finalAnswer);
}
}
抛出的异常是:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1501
at java.lang.AbstractStringBuilder.deleteCharAt(AbstractStringBuilder.java:797)
at java.lang.StringBuilder.deleteCharAt(StringBuilder.java:253)
at problemFourtyEight.main(problemFourtyEight.java:13)
通过打印答案的长度(在去除任何字符之前),它告诉我数字的长度为3001,所以我不明白为什么String索引
1,501被说成是OutOfBounds
。