英文:
How do I print a 2D array of char[][]?
问题
我创建了一个char[][]
的二维数组。我想使用ASCII码打印小写字母。
我编写了代码,但我没有得到预期的结果。我错在哪里?
我知道如果我像answercode一样修复代码,它可以正常工作。但我想知道为什么当我使用我的代码时什么都不会发生,即使控制台中没有a
。
这是我的代码:
package array;
public class Alphabet {
public static void main(String[] args) {
char[][] alphabets = new char[13][2];
alphabets[0][0] = 'a';
for (int i = 0; i < alphabets.length; i++) {
for (int j = 0; j < alphabets[i].length; j++) {
System.out.print(alphabets[i][j]);
alphabets[i][j]++;
}
System.out.println();
}
}
}
预期输出是:
a b
c d
e f
...
...
y z
英文:
I made 2 dimensional array of char[][]
. I want to print small letter by using ASCII code.
I wrote the code, but I don't have the expected results. Where I'm wrong?
I know if I fix code like answercode it works well. But I want to know why nothing happens when I use my code, even if there are no a
in console.
Here is my code:
package array;
public class Alphabet {
public static void main(String[] args) {
char[][] alphabets = new char[13][2];
alphabets[0][0] = 'a';
for (int i = 0; i < alphabets.length; i++) {
for (int j = 0; j < alphabets[i].length; j++) {
System.out.print(alphabets[i][j]);
alphabets[i][j]++;
}
System.out.println();
}
}
}
The expected output is:
a b
c d
e f
...
...
y z
答案1
得分: 0
您的代码完美运行,但您看不到字母,因为您没有将所有的char
放入char[][]
中。
所以,您可以创建一个简单的名为populate的方法,如下所示:
private static void populate(char[][] alphabets) {
char c = 'a';
for (int i = 0; i < alphabets.length; i++) {
for (int j = 0; j < alphabets[i].length; j++) {
if (c <= 'z') { //我们想要从'a'到'z'
alphabets[i][j] = c;
c++; //获取下一个字母
}//if
}//for
}//for
}//populate
您可以调用这个方法,而不是alphabets[0][0] = 'a';
。所以主要的代码将是:
public static void main(String[] args) {
//创建char[][]
char[][] alphabets = new char[13][2];
//填充char[][]
populate(alphabets);
//打印输出
for (int i = 0; i < alphabets.length; i++) {
for (int j = 0; j < alphabets[i].length; j++) {
System.out.print(alphabets[i][j]);
alphabets[i][j]++;
}
System.out.println();
}
}
这是输出结果(我在jdoodle上测试过):
英文:
Your code works perfectly, but you can't see the alphabet because you haven't put all the char
in the char[][]
.
So, you can create a simple method called populate, like this:
private static void populate(char[][] alphabets) {
char c = 'a';
for (int i = 0; i < alphabets.length; i++) {
for (int j = 0; j < alphabets[i].length; j++) {
if (c <= 'z') { //we want from 'a' to 'z'
alphabets[i][j] = c;
c++; //get the next letter
}//if
}//for
}//for
}//populate
You can call this method instead of alphabets[0][0] = 'a';
. So the Main code will be:
public static void main(String[] args) {
//Create char[][]
char[][] alphabets = new char[13][2];
//populate char[][]
populate(alphabets);
//print the output
for (int i = 0; i < alphabets.length; i++) {
for (int j = 0; j < alphabets[i].length; j++) {
System.out.print(alphabets[i][j]);
alphabets[i][j]++;
}
System.out.println();
}
}
This is the output (I've tested it on jdoodle):
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论