简体   繁体   中英

String out of range - java

I want get a String like this "S s jA a sdL l swA a sdM m " and print a String like this "salam" (print characters as String that are next to a Capital)

I wrote this :

    import java.util.Scanner;

public class Temp {
    public static void main(String[] args) {
        char[] capitalalphabet = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
        Scanner input = new Scanner(System.in);
        String s1 = input.next();
        StringBuffer s2 = new StringBuffer();

        for (int i=0 ; i < s1.length() ; i++) {
            for (int j = 0; j < capitalalphabet.length; j++) {
                if (s1.charAt(i) == capitalalphabet[j]){
                    int k = 0 ;
                    s2.setCharAt(k , s1.charAt(i+1));
                    k++;
                }

            }
        }
        System.out.println(s2);


    }
}

and i got this error :

    SAhfdsdEDsa
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
    at java.lang.StringBuffer.setCharAt(StringBuffer.java:257)
    at Temp.main(Temp.java:14)

It happens at this line:

 s2.setCharAt(k, s1.charAt(i+1));

According to the documentation :

Throws: StringIndexOutOfBoundsException - if start is less than zero, or greater than the length of this object.

Since your s2 string is empty (its length is 0), you're exceeding the bounds when you try to add to it.

Also, since your k variable is always initialized to zero right before the setChatAt method, and it's only defined inside the if-statement block, you'll always be setting at index 0, even if you could.

I'd suggest you just simply try to use StringBuilder instead, as well as discard the messy loop of captial letters - their ASCII code is sequential, you could simply ask if character is in range:

for (int i=0 ; i < s1.length()-1; i++) {
    char c = s1.charAt(i);
    if (c >= 'A' && c <= 'Z') {
        s2.append(s1.charAt(i+1));
    }
}
System.out.println(s2);

Note that the loop scans until the index before last, since it might access the next index (and since there's no need to check the last character - it cannot be followed by anything, capital or otherwise).

Note you could also replace the if condition with Character.isUpperCase(c) which is more readable and elegant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM