0

Following is the code i tried

import java.lang.String.*;
import java.io.*;

public class Main {
public static void main(String[] args) {
String [][] array1 = new String[][] {
    {"One"},
    {"One", "Two", "Three"},
    {"One"," Four"," Five"},
    {"One"," Four", "Six"," Seven"},
    {"Seven", "Eight"," One"},
    {"One"},
    {"One"," Nine"},
    {"One", "Nine"," Seven"},
    {"One"," Nine"}
};
for (int row1=0;row1<=array1.length;row1++){
for  ( int cols=1 ;cols<array1[row1].length ;cols++){
System.out.println(array1[0][0] +" "+ array1[row1][cols]);
}
}
}
}

I want to display the elements as

One
One Two
One Three
One Four
One Five
One Four
One Six
One Seven
Seven Eight
Seven One
One
One Nine and so on till the end of the array.

The output is :

One Two
One Three
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
One  Four
One  Five
One  Four
        at javaapplication12.Main.main(Main.java:45)
One Six
One  Seven
One Eight
One  One
One  Nine
One Nine
One  Seven
One  Nine
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Please suggest me what I should do to get the preffered output..Any help will be appreciated ...

1 Answer 1

1

Try Below code

for (String[] tmpArray: array1) {
        if(tmpArray.length == 1)
        { 
            System.out.println(tmpArray[0]);
            continue;
        }
        for (int i = 1; i < tmpArray.length; i++)  {
            System.out.println(tmpArray[0] + " " + tmpArray[i]);
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.