vishnu
vishnu

Reputation: 740

Alternate display of 2 strings in Java

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?

Upvotes: 2

Views: 2366

Answers (6)

BiswajitDV
BiswajitDV

Reputation: 1

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));
            }
        }
    }
}
}

Upvotes: 0

Dilip
Dilip

Reputation: 1

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));
            }

        }

    }
}

}

Upvotes: 0

Pshemo
Pshemo

Reputation: 124265

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).

Upvotes: 2

prashant thakre
prashant thakre

Reputation: 5147

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()); 
}

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122008

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]);
           }

Upvotes: 2

Eran
Eran

Reputation: 393936

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

Upvotes: 0

Related Questions