Mutliply characters in Java

36 Views Asked by At
public class String_multiply {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        String str = s.next();
        int len = str.length();
        int i=0;
        String c_s = new String();
        while(i<len) {
            if (Character.isAlphabetic(str.charAt(i))){
                char c =  str.charAt(i);
                c_s = String.valueOf(c);
                i++;
            }
            String n ="";
            while(Character.isDigit(str.charAt(i))) {
                n+=str.charAt(i);
                i++;
            }
            int inte =Integer.parseInt(n);
            System.out.print(c_s.repeat(inte));
        }
    }
}

I don't know, where I went wrong. I get "String index out of range: 4" as error.

Input: a1b4c3

Output: abbbbccc

1

There are 1 best solutions below

0
Thomas Kläger On

The problem is this loop:

while(Character.isDigit(str.charAt(i))) {
    n+=str.charAt(i);
    i++;
}

It tries to read a sequence of digits from the string, but it doesn't stop if i goes past the end of the string.

You must stop that loop if i == len:

while(i < len && Character.isDigit(str.charAt(i))) {
    n+=str.charAt(i);
    i++;
}