Home > Mobile >  String index out of bounds but cant figure out why
String index out of bounds but cant figure out why

Time:11-11

So I'm working on this code for practice and its supposed to take all the numbers between 2 "-"s and add them together. I'm supposed to convert the strings to ints as part of the problem. (This is my first time using this website so apologies if anything is formatted oddly)

This is my first time using the Integer.parseInt() so maybe it has to do with that but I think it has to do with how I set up my index I'm not quite sure. this is everything I have so far. Ive tried to chnage around the order of the index as well as remove the 1 and even create a variable with just parts of the string but nothing seems to work. the error im getting reads as follows:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 4, end 3, length 8
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3751)
    at java.base/java.lang.String.substring(String.java:1907)
    at Social.chopAndAdd(Social.java:23)
    at Social.toString(Social.java:28)
    at Social.main(Social.java:33)

Below is what I currently have coded

public class Social{
  private String socialNum;
  private int sum;

public Social(){
 socialNum = null;
 sum = 0;
}
public Social(String soc){
 socialNum = soc;
}
public void setSocial(String w){
 socialNum = w;
}
public int chopAndAdd(){

  sum = ((Integer.parseInt(socialNum.substring(0, socialNum.indexOf("-")))));
  sum = sum   (Integer.parseInt(socialNum.substring((socialNum.indexOf("-")   1), socialNum.indexOf(""))));
  sum = sum   (Integer.parseInt(socialNum.substring((socialNum.lastIndexOf("-")), socialNum.length() -                           1)));
   return sum;
}
public String toString(){
     return "SS# "   socialNum   " has a total of "   chopAndAdd();
}
  public static void main( String args[] ){
    Social test = new Social();
    test.setSocial("102-2-12");
    System.out.print(test.toString());
    //add test cases for each given input   
}
  }

CodePudding user response:

The main problem is with indexOf. The first time you call it, try preserving that index. For example:

int ndx = socialNum.indexOf("-")

That way when you look for the next dash you can use it this way:

socialNum.indexOf("-", ndx 1)

As in: find me the next dash

CodePudding user response:

Try this.

    public int chopAndAdd() {
        sum = ((Integer.parseInt(socialNum.substring(0, socialNum.indexOf("-")))));
        sum = sum   (Integer.parseInt(socialNum.substring((socialNum.indexOf("-")   1), socialNum.lastIndexOf("-"))));
        sum = sum   (Integer.parseInt(socialNum.substring((socialNum.lastIndexOf("-")   1), socialNum.length())));
        return sum;
    }

or

    public int chopAndAdd() {
        return Stream.of(socialNum.split("-"))
            .mapToInt(Integer::parseInt)
            .sum();
    }
  • Related