2

Basically, I'm trying to integrate the code structure our course textbook tells us to use, which is setting a first, middle, and last part of the string, then printing it using concatenation (structure shown in the code), but get a java.lang.StringIndexOutOfBoundsException.

I have tried messing around with the i and j values in the code, trying to get the index within bounds.

  i = keyboard.nextInt();
  j = keyboard.nextInt(); // decides letter swap spots
  first = word.substring(word.length(),i-1);
  middle = word.substring(i+1,j-1);
  last = word.substring(j+1,(word.length()-1));
  System.out.printf(first + middle + last);

I essentially need the program to swap letter spots of a word (provided by the user) based upon the I and J values. I am getting this error:

java.lang.StringIndexOutOfBoundsException: begin 1, end 0, length 7
    at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3410)
    at java.base/java.lang.String.substring(String.java:1883)

(using the word "hello" as my user input example)

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153
  • 1
    Have you looked at what happens with a short string, and a low i and j, on paper? There's only a few lines of code, just literally write out what happens at each instruction: what would `first` become? Why? (e.g. what are the arguments you're giving the methods you call, and what are they supposed to do according to the documentation) It's a simple exercise that's really effective at letting you quickly realise what you did wrong. – Mike 'Pomax' Kamermans Sep 22 '19 at 06:15
  • Start reading the documentation of [substring](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/String.html#substring(int,int)) - it tells when the exception is thrown: "if the beginIndex is negative, or endIndex is larger than the length of this String object, or beginIndex is larger than endIndex", also read what the meaning of the argument are and then check the actual values of the code (e.g. **begin**Index being `word.length()`) – user85421 Sep 22 '19 at 06:16

0 Answers0