0

This is my code

class demo {
    public static void main(String args[]) {
        String[] str = {
                "MC", "MR", "MS", "M+", "M-", "BACK", "CE", "C", "+-", "ROOT",
                "7", "8", "9", "%", "4", "5", "6", "*", "1/X", "1", "2", "3",
                "-", "=", "0", ".", "+"};
        int z = 0;
        for (int i = 0; i < str.length; i++) {
            for (int j = 0; j < 4; j++) {
                System.out.print(str[z] + " ");
                z++;
            }
            System.out.println();
        }
    }
}

now, what i want is to print them all in a pattern of four columns in one row, but somehow i'm facing ArrayOutOfBoundException in this logic, please tell me if there is any improvement i can do in this code. Thanks in advance

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • 2
    Do you know how to use your debugger? Have you bothered Googling this exception? – tnw Mar 15 '17 at 15:01
  • the problem is your inner loop. consider inserting an if statement inside the inner loop to check if "z" is still less than the length of the array. – Ousmane D. Mar 15 '17 at 15:02
  • Do you understand what that exception means? See: [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](http://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Jesper Mar 15 '17 at 15:03
  • z becomes too big.. z>str.length() thats causes the exception. try to reset it when need it, or dont use it at all – gvlachakis Mar 15 '17 at 15:03
  • You are trying to increment `z` up to `4 * str.length` - I hope you understand why that won't work – UnholySheep Mar 15 '17 at 15:04
  • Actually i know why exception is occuring, but the problem is i'm not getting any other logic,... – Hitesh Sadana Mar 15 '17 at 15:04
  • how can i print them all in 4 columns in a row without exceeding the loop..!! Any idea..!!!! – Hitesh Sadana Mar 15 '17 at 15:07
  • Did you try using a debugger? Or actually executing your code on pen and paper to understand why you are having the problem you are? Given that this looks like a homework assignment, you might want to take more time to understand why this doesn't work. – Brandon McKenzie Mar 15 '17 at 15:12

1 Answers1

2

You could tackle this differently. Just print newline after every 4th value

for (int i = 0; i < str.length; i++) {
    System.out.print(String.format("%6s", str[i]));
    if (i % 4 == 3) {
        System.out.println();
    }
}

Output

MC    MR    MS    M+
M-  BACK    CE     C
+-  ROOT     7     8
 9     %     4     5
 6     *   1/X     1
 2     3     -     =
 0     .     +
Adam
  • 35,919
  • 9
  • 100
  • 137