【问题标题】:Why can't I print the String out of my multidimensional-Array?为什么我不能从我的多维数组中打印字符串?
【发布时间】:2019-08-16 11:54:44
【问题描述】:

我读过其他帖子,而不是只写System.out.println(finalPressedKey); 你应该写System.out.println(Arrays.toString((finalPressedKey));,否则它只会返回保存字符串的位置(据我所知)。

public static String PressedKey[] = new String[2000];

public static String[][] finalPressedKey = {{ "", "", "", "", "", "", "", "", "", "", "", "" }}; // 12

public static String FPK3;

public static void upcounter(KeyEvent e) {

    for (int x = 0; x < PressedKey.length; x++) {

        if (PressedKey[x] != null && PressedKey[x + counter] != null) {

        //FPK counter is supposed to be a line, and counter is where the words are supposed to be saved

        finalPressedKey[FPKcounter][counter] =
        finalPressedKey[FPKcounter] + PressedKey[x + counter];

            System.out.println(Arrays.toString(finalPressedKey));
        }

    }

每当我按下一个按钮时,它都应该保存在我的 PressedKey 数组中,并且 finalPressedKey 应该包含自己,并且 PressedKey (同样,应该只打印数组的最后一个元素),但是相反,它只打印[[Ljava.lang.String;@76f42c4b]

我也尝试过使用Arrays.deepToString();,但它给了我与Arrays.toString();相同的输出

感谢您的帮助!

【问题讨论】:

  • 如果你想如果你使用Arrays.deepToString() 它会工作。您如何发布您的尝试?
  • 否则它只会返回保存字符串的位置--这是打印的对象内部哈希码,与“位置”没有任何关系

标签: java string eclipse multidimensional-array


【解决方案1】:

String[][] 不是二维数组。它是String[] 的数组。区别很微妙,但很重要。

方法Arrays.toString() 接受一个数组,遍历其元素,在所有元素上调用toString(),并添加前缀、后缀和分隔符。既然你给它一个String[][]String[]的数组),它会做以下事情:

  • 遍历元素(每个元素都是一个String[]
  • 在每个元素上调用 toString() - 给出数组的默认 toString() 值 - 即它的内存地址(不是真的,但为此无关紧要)
  • 连接

幸运的是,有一个更简单的方法 - 只需使用 Arrays.deepToString()。这与您预期的一样。

【讨论】:

  • OP 已经“尝试使用Arrays.deepToString();”我敢打赌字符串表示已经在数组中
【解决方案2】:

整个代码我没看懂,但是下面的说法很可疑:

finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter] + PressedKey[x + counter];

因为它将数组 (finalPressedKey[...]) 添加到字符串 (PressedKey[...]),这将导致 strange 文本 - 数组的标准文本表示(由 @987654324 返回@)。 (从数学的角度来看,在赋值之前有 2 个索引 )2D_ 并且对于同一矩阵只有一个在右侧 (1D) 是很奇怪的)

我不确定,因为我们看不到 counter 是什么,但我相信你想要类似的东西:

finalPressedKey[FPKcounter][counter] =
finalPressedKey[FPKcounter][counter] + PressedKey[x + counter];

也就是说,第二行多了一个[counter]

这也可以写成

finalPressedKey[FPKcounter][counter] += PressedKey[x + counter];

【讨论】:

    【解决方案3】:

    如果你只想存储字符串行,普通的 String[] 对你有好处

    finalPressedKey[FPKcounter] += PressedKey[x + counter];
    

    尽管我不建议这样做,但无论您尝试完成什么,因为这将在每次按下键时创建一个新的 String 对象。

    也许以不同的方式提出问题并告诉我们您要做什么。我猜字符串数组可能不是要走的路。

    【讨论】:

      【解决方案4】:

      您必须使用

      打印数组的元素
      for(int i = 0; i<finalPressedKey[0].length; i++){
         for(int j=0; j<finalPressedKey[1].length; j++){
            System.out.println(finalPressedKey[i][j]);
         } 
      }
      
      

      如果我理解正确的话。

      【讨论】:

      • 如果你修复了代码的缩进,OP 可以更好地理解它。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2021-12-13
      • 1970-01-01
      • 2014-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多