Reputation: 89
I have here some code trying to output seat numbers. The output is formatted as such for numRows = 2
and numCols = 3: 1A 1B 1C 2A 2B 2C
My problem below is with my char.forDigit
method. What I am trying to do is input Unicode values (65 being A, 66 being B, etc) and output their respective chars. Any help?
for (int i = 1; i <= numRows; i++){
for (int j = 1; j <= numCols; j++){
System.out.print(i + char.forDigit(65 + j) + " ");
}
}
Upvotes: 1
Views: 76
Reputation: 201447
char
is a primitive type, and you cannot invoke methods on a primitive type. However, it is also an integral type (which means you can perform arithmetic). You could do something like,
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
System.out.printf("%d%c ", 1 + i, 'A' + j);
}
System.out.println(); // <-- Don't forget to create a newline for the next row
}
Additionally, based on your stated objective what I am trying to do is input Unicode values (65 being A, 66 being B, etc) and output their respective chars; I would use a basic cast like
int c = 65;
System.out.println((char) c);
or, printf
again like
int c = 65;
System.out.printf("%c", c);
Both of which output (the requested)
A
Upvotes: 2
Reputation: 647
System.out.print(i +""+ ((char)(65 + j)) + " ");
Explicit Type Conversion or type casting.
Upvotes: 1