Home > Enterprise >  java Index 5 out of bounds for length 5 error while doing while loop
java Index 5 out of bounds for length 5 error while doing while loop

Time:11-02

I'm trying to switch every odd index character with the nearest even index character to it in a string.

public class A3_Q1 {

    public static void main(String... args) {
        System.out.print("Enter the messgae you want to be coded: ");
        
        Scanner in = new Scanner(System.in);
        String msg = in.nextLine();
        
        in.close();
        
        msg = msg.trim();
        char msg1[] =  msg.toCharArray();
        int index = 0;
        
        while (index<msg.length()) {
            msg1[index] = msg1[  index];
            index  ;
        }
    
        System.out.print(msg1); 
    }

}

I tried searching and asking more experienced friends what's wrong but we don't know bare with us all compsci freshmen

CodePudding user response:

What happens if index is msg.length() -1? You will be out-of-range.

So you should check two condition in your loop.

  1. index is odd or even
  2. index and index 1 is not out-of-bound msg.length.

CodePudding user response:

index increments the index first before using the value. index uses the value first before incrementing. That means each iteration increments index by 2. If msg has an odd length (your example 5) and index = 4 you enter the loop. [ index] is evaluated to [5] and you get the exception.

So you have to ignore the last character for odd lenths with while (index<msg.length() - 1)

CodePudding user response:

public static void main(String... args) {
    // Best practice: one instruction per one line
    System.out.print("Enter the message you want to be coded: ");

    // When using System.in you should not close the Scanner
    Scanner scan = new Scanner(System.in);
    String message = scan.nextLine().trim();
    // Best practice: move encoding logic to the separate method
    String convertedMessage = convert(message);
    System.out.println(convertedMessage);
}

public static String convert(String str) {
    // String is immutable, so we have to use StringBuilder to build a new string
    StringBuilder buf = new StringBuilder();

    // does not matter what to use, I prefer for...loop
    for (int i = 0; i < str.length(); i  ) {
        // do not forget to check case for the last index
        if (i == str.length() - 1 || i % 2 != 0)
            buf.append(str.charAt(i));
        else
            // here we have odd and not last index (just use the next one)
            buf.append(str.charAt(i   1));
    }

    return buf.toString();
}

Demo

Enter the message you want to be coded: abcdefghijklmnopqrstuvwxyz
bbddffhhjjllnnpprrttvvxxzz

CodePudding user response:

It will out of bounds because:

while (index<msg.length()) {
            msg1[index] = msg1[  index];
            index  ;
        }

java index start with 0. So if the lengh is 5 it will be 0, 1, 2, 3, 4.

msg1[index] = msg1[  index];

On this line with index 4 you will out of bounds because 4 1 is 5. you need to add something like this

if(  index<msg.length())
  • Related