I need to write a method groupify which takes 2 parameters:
So, the code may print a string which consists of the input string broken into groups with the number of letters specified on the second parameters, if there aren't enough letters in the input string to fill out all the groups, it should fill the final group with "x", so if I groupify("HELLODANY",2), it must return "HE LL OD AN YX"
My code is the following:
package com.company;
import java.util.Random;
public class Main {
public static String gropify(String message,int number) {
String result="";
int len =message.length();
int s=0;
int n=3;
for(int x=0;x<len;++n) {
s = s + number;
result = result + message.substring(x,s);
}
return result;
}
public static void main(String[] args) {
String message= "HELLODANY";
System.out.println(gropify(message, 3));
}
}
But I'm getting the following exception:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12
What should I change?
I would prefer a StringBuilder over many String concatenations (those create temporary immutable String instances). Next, you can test if the current index is evenly divisible by number, if it is then you add a space; then append the actual character to the StringBuilder. Finally, add padding by calculating the remainder of the message length divided by number - append that many X(s). Like,
public static String gropify(String message, int number) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < message.length(); i++) {
if (i != 0 && i % number == 0) {
sb.append(' ');
}
sb.append(message.charAt(i));
}
int pad = message.length() % number;
for (int i = 0; i < pad; i++) {
sb.append('X');
}
return sb.toString();
}
Note that your current approach is flawed, you are adding to s in the loop body, when you hit 12 you exceed the length of your message.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With