Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java – even position letters in String to be categorized

public class UsingArrayGetEvenLettersFromString {

    public static void main(String[] args) {
        // even letters
        String str = new String("hello");
        char[] ch = str.toCharArray();
        char[] eCh = {};
        char[] oCh = {};
        System.out.println("length :"+ch.length);
        
        for(int i=0; i<ch.length; i++) {
            if(ch[i]%2 == 0) {
                eCh[i] = ch[i]; 
            }
            else {
                oCh[i] = ch[i];
            }
        }
        for (char c : eCh) {
            System.out.println(c);
        }
        for (char c : oCh) {
            System.out.println(c);
        }
    }
}
Error: length :5
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
    at Strings.UsingArrayGetEvenLettersFromString.main(UsingArrayGetEvenLettersFromString.java:15)

I do not get what it does mean as far as I know … please suggest

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Because when you make array you can’t change its size, and when you make array like this

char[] eCh = {};

it takes its length as zero.

You must give the array length first like this

char[] eCh = new char[str.length()];
char[] oCh = new char[str.length()];

Then you can use it normally.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading