英文:
How can I convert numbers into letters?
问题
以下是翻译好的内容:
我有这段代码,它会生成一个二维矩阵,在第一列中有4个数字之一,在第二列中也有4个数字之一(但两个值不能相同)。但现在,我想要将这些数字转换为字母 - 所以我想要的不是数字1、2、3或4,而是字母a、b、c或d。我知道我必须通过ASCII编码来解决这个问题,但我不知道该怎么做。
是的,我知道,在StackOverflow上确实有一个关于这个问题的帖子,但我不知道如何将那个帖子中的方法实现到我的类中。这两行代码对我没有帮助,因为我有这个特定的代码,而且我对Java或编程一般都很新。
以下是您提供的代码的翻译部分:
public class Scratch {
public static void main(String[] args) {
Character[][] generator = new Character[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 ? 'a' : (x < 0.5 ? 'b' : (x < 0.75 ? 'c' : 'd'));
} else {
do {
double y = Math.random();
generator[i][j] = y < 0.25 ? 'a' : (y < 0.5 ? 'b' : (y < 0.75 ? 'c' : 'd'));
} while (generator[i][j].equals(generator[i][0]));
}
System.out.print(generator[i][j] + " ");
}
System.out.println();
}
}
}
英文:
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();
}
}
}
答案1
得分: 2
char
实际上是int
,你可以在char
和int
之间使用-
和+
:
// 1 - a; 26 - z
public static char convertToLetter(int num) {
return (char)('a' - 1 + num);
}
英文:
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);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论