Matt
Matt

Reputation: 36

Why does my for loop give different results in Android studio oppose to eclipse (java)

I copy and pasted some code from my eclipse project into my android studio java file. I fixed up any variable declaration to fit android studio, but my code does not perform the same. In particular my for loop:

 int z = 0;
 for (int i = 0;i < translatable.length;i++){
      translatable[i] = Chars[z] + Chars[z+1];
      z+=2;
 }

when used in eclipse, if i enter matthew it will return:

ma tt he wz

but when used in my android studio application it returns:

m at th ew

*i have made a playfair cipher which i am trying to convert to an android app.

to add more context i will add the previous code also, in which i think works fine but just in case someone is able to pick up on something im not:

encrypt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String[][] key = new String[5][5];
            String[] filler =
                    {
                            "a","b","c","d","e",
                            "f","g","h","i","k",
                            "l","m","n","o","p",
                            "q","r","s","t","u",
                            "v","w","x","y","z"
                    };


            String txt = text.getText().toString();


            String[] words = txt.split(" ");

            int alphNum = 0;
            String joinTxt ="";

            for (int i = 0; i < words.length;i++){

                if(words[i].length() % 2 != 0){

                    words[i] = words[i] + "z";

                    alphNum = alphNum + words[i].length();
                    joinTxt = joinTxt + words[i];


                } else {

                    alphNum = alphNum + words[i].length();
                    joinTxt = joinTxt + words[i];

                }
            }

            String[] Chars = joinTxt.split("");

            String[] translatable = new String[Chars.length / 2];

            int z = 0;
            for (int i = 0;i < translatable.length;i++){
                translatable[i] = Chars[z] + Chars[z+1];
                z+=2;
            }

Im finding it hard to understand why I am encountering this problem and do not understand the logic. If someone could point me in the right direction that would be great as the exact same code works fine in another IDE. Sorry about my naming conventions.

EDIT: after doing some more debugging, i found i was wrong in thinking my for loop was the problem for this.

Each split statement used has left a leading empty array item, and using the necessary methods i cant seem to get rid of them. i have managed to work around it by indexing from 1 instead of 0. I will do more research into the split method and why this is happening. Thank you for your help.

Upvotes: 0

Views: 111

Answers (1)

Related Questions