-4
public class Tester {
    static List<String> columnNames(int n) {

        List<String> result = new ArrayList<String>();
        String alphabets[] = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
        StringBuilder sb = new StringBuilder();
        for(int j = 0; j < n; j++){
            int index = j/26;
            char ch = (char) (j % 26 + 'A');
            sb.append(ch);
            String item = "";
            if(index > 0) {
                item += alphabets[index-1];
            }
            item += alphabets[j % 26];
            result.add(item);
        }
        sb.reverse();
        return result;
    }

I use this function, It seems ok but I give 703 input(702 is ok but 703 is not ok) , I get an error

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 26
    at example.Tester.columnNames(Tester.java:20)
    at example.Tester.main(Tester.java:34)

Please help me. If input is 703 must be A,B,.......AA,AB,....,ZZ,AAA,AAB,AAC...

  • 3
    Possible duplicate of [What is IndexOutOfBoundsException? How can I fix it?](https://stackoverflow.com/questions/40006317/what-is-indexoutofboundsexception-how-can-i-fix-it) – Joe C Jul 14 '18 at 18:05
  • `colName` is an empty String and then you try to call the `char` at a non zero index. I think you got `result` and `colName` mixed up a few times – GBlodgett Jul 14 '18 at 18:21

1 Answers1

1

This exeption apperiance on at this line

colName = (position == 0 ? 'Z' : colName.charAt(position > 0 ? position - 1 : 0)) + colName;

because ypu try to get colName.charAt(12)(if input equals 13) from empty String.

If you want to get this output(A, B, C, D, E, F, G, H, I, J, K, L, M) try this:

public class Test {
  static String columnNames(int n) {
    String capitalAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    return capitalAlphabet.substring(0, n);

  }

  public static void main(String[] args) throws IOException {
    Scanner in = new Scanner(System.in);
    System.out.println("sayi giriniz..");
    Integer input = in.nextInt();

    String result = columnNames(input);
    System.out.println(String.join(", ", result.split("")));
  }

}

Input

13

Output

A, B, C, D, E, F, G, H, I, J, K, L, M
Maxim Kasyanov
  • 938
  • 5
  • 14