2

I have a java program where the following is what I wanted to achieve:

first input: ABC

second input: xyz

output: AxByCz

and my Java program is as follows:

    import java.io.*;

    class DisplayStringAlternately 
    {
        public static void main(String[] arguments)
        {
            String firstC[], secondC[];

            firstC = new String[] {"A","B","C"};
            secondC = new String[] {"x","y","z"};

            displayStringAlternately(firstC, secondC);        
        }

        public static void displayStringAlternately (String[] firstString, String[] secondString)
        {
           int combinedLengthOfStrings = firstString.length + secondString.length;

           for(int counter = 1, i = 0; i < combinedLengthOfStrings; counter++, i++)
           {
               if(counter % 2 == 0)
               {
                   System.out.print(secondString[i]);
               }
               else 
               {
                   System.out.print(firstString[i]);
               }
           }
        }        
    }

however I encounter the following runtime error:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
    AyC at DisplayStringAlternately.displayStringAlternately(DisplayStringAlternately.java:23)
        at DisplayStringAlternately.main(DisplayStringAlternately.java:12)
    Java Result: 1

What mistake is in my Java program?

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
vishnu
  • 730
  • 2
  • 6
  • 26

6 Answers6

2

As you commented, If both arrays length is same, you can simply do

 firstC = new String[] {"A","B","C"};
 secondC = new String[] {"x","y","z"};

Then

          for(int i = 0; i < firstC.length; i++)  {
                   System.out.print(firstC[i]);
                   System.out.print(secondC[i]);
           }
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
2

If both arrays have same length for loop should continue while i < anyArray.length.

Also you don't need any counter to determine from which array you should print first. Just hardcode that first element will be printed from firstString and next one from secondString.

So your displayStringAlternately method can look like

public static void displayStringAlternately(String[] firstString,
        String[] secondString) {
    for (int i = 0; i < firstString.length; i++) {
        System.out.print(firstString[i]);
        System.out.print(secondString[i]);
    }
}

Anyway your code throws ArrayIndexOutOfBoundsException because each time you decide from which array print element you are incrementing i, so effectively you are jumping through arrays this way

 i=0     i=2
{"A","B","C"};

{"x","y","z"};    
     i=1     i=3 
             ^^^-here is the problem

so as you see your code tries to access element from second array which is not inside of it (it is out of its bounds).

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • thank you. Though there are other acceptable answers, yours has more in depth explanation. thank you very much – vishnu Aug 01 '14 at 16:17
0

Using the combined length of the Strings is wrong, since, for example, secondString[i] would cause an exception when i >= secondString.length.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

Try the below working code with high performance

public static void main(String[] arguments)
{
    String firstC[], secondC[];

    firstC = new String[] {"A","B","C"};
    secondC = new String[] {"x","y","z"};
    StringBuilder  builder = new StringBuilder();
    for (int i = 0; i < firstC.length; i++) {
        builder.append(firstC[i]);
        builder.append(secondC[i]);
    }
    System.out.println(builder.toString()); 
}
prashant thakre
  • 5,061
  • 3
  • 26
  • 39
0

public class concad {

public void main(String[] args) {

    String s1 = "RAMESH";
    String s2 = "SURESH";

    int i;
    int j;

    for (i = 0; i < s1.length(); i++) {
        System.out.print(s1.charAt(i));
        for (j = i; j <= i; j++) {
            if (j == i) {
                System.out.print(s2.charAt(j));
            }

        }

    }
}

}

  • 1
    What is the purpose of the second `for` loop? It has only one iteration ... _always_. And the value of `j` is _always_ the same as in `i`. – Tom Mar 05 '15 at 19:28
0

I have taken two strings as mentioned.Then pass one counter variable in inner for-loop with second string,Then for every even position pass with code "counter%2".Check this out if any concern then comment below.

public class AlternatePosition {

public static void main(String[] arguments) {

    String abc = "abcd";
    String def = "efgh";
    displayStringAlternately(abc, def);
}

public static void displayStringAlternately(String firstString, String secondString) {
    for (int i = 0; i < firstString.length(); i++) {
        for (int counter = 1, j = 0; j < secondString.length(); counter++, j++) {
            if (counter % 2 == 0) {
                System.out.print(secondString.charAt(i));
                break;
            } else {
                System.out.print(firstString.charAt(i));
            }
        }
    }
}
}
  • it would be better if you could had some description in your answer. It would be more useful for future readers – goto Jan 19 '17 at 10:38