0

Please bear with me. I am new to java but I am struggling to code ..but I am sure I will overcome it one day so please help me ..


String array - Palindrome is what i am working on to build up my logical sense in java. This is what I have written so far

public class Strings1 {

public static void main(String[] args) {
    String[]  str = {"dadad", "Boomot", "mojmom"};
    String[] str1=str;
    String[] str2={};
    int i=0;
    int j=0;
    int k=0;
    char c='0';
    char e='0';
    int s = str.length;

    System.out.println("number of elements in the array" + s);
try{    
    x: for(; i<s; i++){
        y:  for( j=i,k=str[i].length()-1; k>=0; j++,k--){ //j=0; k=5

             c = (str[i].charAt(j)); // 0
             e = (str[i].charAt(k)); //5

             if(c==e)
             {
                 str2[k] = Character.toString(c);
                 continue;
             }
             else 
                 break y;

            }
            System.out.println(str[2]);
        }
}catch (Exception ex){

    ex.printStackTrace();
}

    }

}

Error :- ------------ number of elements in the array3 java.lang.ArrayIndexOutOfBoundsException: 4 at Strings1.main(Strings1.java:25)

how should I go about it? Please help.

fvu
  • 32,488
  • 6
  • 61
  • 79
  • 1
    You'd do better to isolate the exact line of the error, and before that, print out a few known things - the length of the array you're indexing into, your current index position, etc. That will help you diagnose the problem a ton faster. – Makoto Feb 02 '14 at 17:40
  • The exception gives you a hint - you are trying to read past the end of the array. Best thing to do here is to revisit your formula, on paper, and see where you are not doing the proper boundry checks and what makes you go outside the array. – Ewald Feb 02 '14 at 17:41
  • may be i should try and print the values and see where i am going wrong .. may be work on one string first and check for palindrome and then work on string arrays .. i think i have just lost the control of the nested loops! – Beginner_in_java Feb 02 '14 at 18:04

5 Answers5

0

k is str[i].length - 1. that means, k can be 5, and str[i] can only give you some values if i is between 0 and 2 since there are just 3 elements in str array. Hence the array out of bound exception error!

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78
0

This:

str2[k] = Character.toString(c);

Since str2 is an empty array, every element access must fail.

What you perhaps want is to work on a single stringt to detect a palindrome (or whatever you want to do). Write a method for it. Then, write another method that handles an array of strings and uses your method for the single string. This will help you avoid nesting loops and loose control of the indexes.

Ingo
  • 36,037
  • 5
  • 53
  • 100
  • funny, my name is Aniket and your name is `ingo`, and my full name is `Aniket Inge` lol! – Aniket Inge Feb 02 '14 at 17:45
  • //This works ==> public class Strings1 { public static void main(String[] args) { String[] str = {"dadadad"}; String reverse =""; int len = str[0].length(); int i=0; System.out.println(len);//7 for(i=len-1;i>=0;i--){ reverse = reverse + str[0].charAt(i); } System.out.println(reverse); } } – Beginner_in_java Feb 02 '14 at 18:51
0

The size of the array str2 is 0 and trying to insert the entry in array on line str2[k] = Character.toString(c); Please initialise the array str2 as String[] str2=new String[length]; and move ahead

Kick
  • 4,823
  • 3
  • 22
  • 29
0
 k=str[i].length()-1;

i = 0, first element of str is "dadad", length = 5, k = now 4.

str2[k] = Character.toString(c);

This array has no elements and throws ArrayIndexOutOfBoundsException

WonderWorld
  • 956
  • 1
  • 8
  • 18
0

Not sure what you are trying to do. That inner loop looks fishy, and you have picked up a bad habits here.

Try to work without labels, eschew continue and break if you can, use locally declared variables (i.e. declare them only when you need them, not earlier) and do not try to optimize early (i.e. compute str.length() whenever you need it, it really costs you nothing).

Additionally, use assertions to verify that what you assume is indeed true. Do not forget to start you program with the -ea option to enable the asserts.

A bit of editing to show what I mean:

class Test {

    public static void main(String[] args) {
        String[] str = { "dadad", "Boomot", "mojmom" };
        String[] str1 = str;
        String[] str2 = {};

        System.out.println("number of elements in the array " + str.length);

        try {
            for (int i = 0; i < str.length; i++) {
                boolean stop = false;
                for (int j = i, k = str[i].length() - 1; k >= 0 && !stop; j++, k--) { // Work on this!!!!

                    assert 0<=j && j<str[i].length();
                    assert k<=j && k<str[i].length();

                    char c = (str[i].charAt(j)); 
                    char e = (str[i].charAt(k));

                    if (c == e) {
                        str2[k] = Character.toString(c);
                    } else {
                        // NOPE!
                        stop = true;
                    }

                }
                System.out.println(str[2]);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}
David Tonhofer
  • 14,559
  • 5
  • 55
  • 51
  • Sorry david .. i know i am bad at it now .. the entire thing looks muddled up to me already .. so may be i should try and print the values and see where i am going wrong .. may be work on one string first and check for palindrome and then work on string arrays .. i think i have just lost the control of the nested loops! – Beginner_in_java Feb 02 '14 at 18:03
  • Keep at it! Good hunting! – David Tonhofer Feb 02 '14 at 18:05
  • This works =======>public class Strings1 { public static void main(String[] args) { String[] str = {"dadadad"}; String reverse =""; int len = str[0].length(); int i=0; System.out.println(len);//7 for(i=len-1;i>=0;i--){ reverse = reverse + str[0].charAt(i); } System.out.println(reverse); } } – Beginner_in_java Feb 02 '14 at 18:49
  • @Beginner_in_java This "reverse" the string indeed. See also: [reversing-an-array-in-java](http://stackoverflow.com/questions/12678781/reversing-an-array-in-java) – David Tonhofer Feb 02 '14 at 20:48
  • Hi David, Thanks for the suggestion but really I don't want to use the collection classes now.. i want to learn it the hard way first and get my logics straight in java .. i really want to use the loops and work my way out of it .. so once i am confident .. i will use the collections and reverse functionality that java provides. What do u think? am i on the right track? – Beginner_in_java Feb 03 '14 at 16:41
  • Yes, that is good. Myself, I started out with languages that did not even have any extensive library set, one had to write everything oneself. Also, use [JUnit](http://junit.sourceforge.net/doc/testinfected/testing.htm) to write simple code to test what you did. Seriously, it is actually fun & productive. Also, sometimes read the code of other people. I remember [Sedgewick's 'Algorithms'](http://algs4.cs.princeton.edu/home/) and [Niklaus Wirth's 'Algorithms and Data Structures'](http://en.wikipedia.org/wiki/Algorithms_%2B_Data_Structures_%3D_Programs).... – David Tonhofer Feb 04 '14 at 17:48