Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my program throwing a StringIndexOutOfBounds exception?

I am writing a program to calculate:

1^1 + 2^2 + 3^3 + ... + 1000^1000 = ?

Once it has calculated it I want to remove all of the digits in the answer besides the last ten digits, and then print the final ten digits on the screen. To remove all of the other digits I am using the StringBuilder.deleteCharAt() method, however, this is causing me some problems. I have provided my code below:

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);
  }
}

The exception thrown is:

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)

From printing out the length of the answer (before removing any characters), it tells me the length of the number is 3001, so I can't understand why the String index 1,501 is said to be OutOfBounds.


1 Answers

Your error is that this code:

StringBuilder sb = new StringBuilder((answer.toString()));
for(int k = 0; k <= (answer.toString().length() - 10); k++) {
  sb.deleteCharAt(k);  //Line 13 is here.
}

Makes the string shorter as it goes, due to the mutability of string builder. You want:

System.out.println(answer.substring(answer.length()-10))

This also has the advantage of speed, if that matters to you.

like image 146
Others Avatar answered Apr 29 '26 10:04

Others



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!