-1

I have this code, which generates me a 2D matrix with one of 4 numbers in the first column and one of 4 numbers in the second column (but both values must not be same). But now, I want to convert the numbers into letters - so instead of the numbers 1, 2, 3 or 4 i wanna have the letters a, b, c or d. I know I have to solve this somehow via the ascii coding, but i don't know how to do it.

And yes, I know, there is exactly this question here in stackoverflow, but I don't know how to implement the method from that question in my class. These 2 lines of code don't help me, because I have this specific code and I'm really new to java or coding in general.

public class scratch{
  public static void main(String[] args) {

    Number[][] generator = new Number[10][2];
    for (int i = 0; i < generator.length; i++) {
      for (int j = 0; j < generator[i].length; j++) {
        if (j == 0) {
          double x = Math.random();
          generator[i][j] = x < 0.25 ? 1 : (x < 0.5 ? 2 : (x < 0.75 ? 3 : 4));
        } else {
          do {
            double y = Math.random();
            generator[i][j] = y < 0.25 ? 1 : (y < 0.5 ? 2 : (y < 0.75 ? 3 : 4));
          } while (generator[i][j].equals(generator[i][0]));
        }
        System.out.print(generator[i][j] + "  ");
      }
      System.out.println();
    }
  }
}
Klippspringer
  • 97
  • 1
  • 7
  • 1
    Does this answer your question? [How do I convert a number to a letter in Java?](https://stackoverflow.com/questions/10813154/how-do-i-convert-a-number-to-a-letter-in-java) – mkrieger1 Oct 23 '20 at 07:41
  • Do you want to store them as letters instead or still store them as numbers but just print them as letters? – Rup Oct 23 '20 at 07:41
  • @mkrieger1 I had already found this post, but I couldn't do anything with it – Klippspringer Oct 23 '20 at 07:44
  • 1
    What was the problem? – mkrieger1 Oct 23 '20 at 07:44
  • @Rup i want to print them as letters – Klippspringer Oct 23 '20 at 07:45
  • Using the other code: is the problem copying the functions from the other question into this class? You'd need to make sure they were marked static. Or calling them? You just need to `System.out.print(getCharForNumber(generator[i][j]) + " ");` – Rup Oct 23 '20 at 07:59
  • You can possibly just do `System.out.print(((char)('a' + generator[i][j] - 1)) + " "); Although you may also need to convert that into a string if it won't let you add a char to a string in that order - I can't remember. – Rup Oct 23 '20 at 08:00

1 Answers1

2

char is actually int, you can use - and + between char and int:

// 1 - a; 26 - z
public static char convertToLetter(int num) {
    return (char)('a' - 1 + num);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35