0

I need to make the following code print the letters of the alphabet instead of ints. How do I do it?

import java.util.*;
import java.math.*;

public class Main {
    String[] letters= {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",
            "O", "P", "Q", "R", "S", "T", "U", "W", "X", "Y", "Z"};
    public static void main(String[] args) {

        //create the grid
        final int rowWidth = 10;
        final int colHeight = 10;

        Random rand = new Random();

        int [][] board = new int [rowWidth][colHeight];

        //fill the grid
        for (int row = 0; row < board.length; row++) {

            for (int col = 0; col < board[row].length; col++) {

                board[row][col] = rand.nextInt(25);
            }
        }

        //display output
        for(int i = 0; i < board.length; i++) {

            for(int j = 0; j < board[i].length; j++) {

                System.out.print(board[i][j] + " ");
                //System.out.println();
            }
            System.out.println();
        }

    } //end of main
} //end of class Main
1
  • 2
    It's usually a good idea to step through your code in the debugger, checking the values of the variables you are accessing. This would have solved your problem. Commented Sep 19, 2012 at 16:57

3 Answers 3

9

I suppose:

System.out.print(letters[board[i][j]]);

As pointed out in the comments, you need to make letters static (and while you are doing that, why not make it private and final too).

Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct solution, but it's noteworthy that for it to work, you also need to either move letters inside main() or declare it a static
5

Note that you don't need a letters array.

board[i][j] + 'A'

would have worked as well.

Comments

0

I would use the range of the ASCII code for the letter in A -Z range, like

for (int i = 65 ; i <= 90; i++) {
// convert int to char and print out
    char c = (int) i;
    System.out.println("" + c);
}

Comments

Your Answer

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