英文:
Counting using a multidimension array
问题
我想创建一个多维数组来进行计数。
这是我目前拥有的代码,但我不知道接下来该怎么做。当我将其打印出来时,我希望它看起来像是 0,1,2,3,4,5,6,7,8,9,10 等。
public static void main(String[] args) {
int car[][] = new int[4][4];
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
<details>
<summary>英文:</summary>
I want to create an multidimensional array that will count.
This is the code I have so far and don't know where to go from here. When I print this out I want it to look like 0,1,2,3,4,5,6,7,8,9,10,etc.
public static void main(String[] args) {
int car[][] = new int[4][4];
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
</details>
# 答案1
**得分**: 1
你正在创建一个空数组,以便每个字段都具有值0。
尝试这样做:
```java
public static void main(String[] args) {
int car[][] = new int[4][4];
int index = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = index++;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
英文:
you're creating empty array so every field has value 0
try this:
public static void main(String[] args) {
int car[][] = new int[4][4];
int index = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = index++;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
}
</details>
# 答案2
**得分**: 0
你需要在打印之前设置这些值。
```java
for (int row = 0; row < car.length; row++) {
for (int col = 0; col < car[1].length; col++) {
car[row][col] = row * 4 + col;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
但是这样使用多维数组是愚蠢且没有意义的。根据我的经验,多维数组的实际应用范围远比人们在学习时玩弄它们的范围要窄得多。
英文:
You need to set the values before printing them
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = row * 4 + col;
System.out.print(car[row][col] + ",");
}
System.out.println();
}
But it's silly and pointless to use a multi-dimensional array like this.In my experience, Multi-dimensional arrays are useful in a much more limited scope than how people play with them when they are learning.
答案3
得分: 0
public static void main(String[] agrs) {
int car[][] = new int[4][4];
int i = 0;
for (int row = 0; row < car.length; row++) {
for (int col = 0; col < car[1].length; col++) {
car[row][col] = i++;
System.out.print(car[row][col] + ",");
}
}
}
英文:
Use this:
public static void main(String[] agrs) {
int car[][] = new int[4][4];
int i = 0;
for(int row = 0; row < car.length; row++){
for(int col = 0; col < car[1].length; col++){
car[row][col] = i++;
System.out.print(car[row][col] + ",");
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论