【问题标题】:why does this for loop always only adds 1's to the array [closed]为什么这个for循环总是只向数组添加1 [关闭]
【发布时间】:2021-10-22 19:43:54
【问题描述】:

我在 java 中创建了一个二维字符串数组,在最后一行中,索引为 6,我想在数组的每一秒空间中放入从 1 到 7 的数字。我的代码如下所示:

    for(int i = 1; i < columns; i += 2) {
        int number = 1;
        fieldArray[6][i] = Integer.toString(number);
        number++;
    }

我的问题是二维数组最后一行的输出是这样的:

null 1 null 1 null 1 null 1 null 1 null 1 null 1 null 

我不明白为什么,我理解 for 循环的方式是,在第一次迭代中,它从索引 1 开始,添加变量号的内容,该变量号被转换为字符串以适合字符串数组,那么变量number加一,下一次迭代,index为3,number为2,但是index 3的内容也是1,为什么呢?

数组中的空值是故意存在的,我想使用相同类型的 for 循环添加不同的内容,但稍后使用不同的偏移量。

【问题讨论】:

  • 请阅读:How to debug small programs --- "为什么这个 for 循环总是只向数组添加 1" - 因为您在解析之前将其设置为 1 .尝试使用Integer.toString(i) 而不是Integer.toString(number)
  • 但是我要放入number变量的值,迭代器i只是为了数组的索引?

标签: java arrays for-loop multidimensional-array


【解决方案1】:

在这里,您每次都定义 number 变量,每次迭代将其设置为 1。
您应该在 for 循环之外定义 number,在它之前。
像这样的:

int number = 1;
for(int i = 1; i < columns; i += 2) {
    fieldArray[6][i] = Integer.toString(number);
    number++;
}

【讨论】:

  • 这是最基本的错误,不好意思哈哈,非常感谢
  • 没关系。如果这解决了您的问题,请接受表明问题已解决的答案。
【解决方案2】:

但是我想放入number变量的值,迭代器i只是为了数组的索引? ——

您的最终要求中缺少一些细节。有一件事是最好使用变量而不是未分配的常量。

int number = 1;
int rows = 7;
int columns = 15;
String[][] fieldArray = new String[rows][columns];
for (int i = 1; i < columns; i += 2) {
    fieldArray[6][i] = Integer.toString(number);
    number++;
}

for (String[] s : fieldArray) {
    System.out.println(Arrays.toString(s));
    
}

打印

[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
[null, 1, null, 2, null, 3, null, 4, null, 5, null, 6, null, 7, null]

【讨论】:

  • 我确实这样做了,这只是我的一些代码,看起来不错,打印出数组的方法看起来比我现在做的更好,谢谢
  • 好的。我不确定,所以我想我会寻求一些澄清。
猜你喜欢
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 2013-04-01
  • 2015-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多