gpt4 book ai didi

java - 将 int[][] 转换为 String

转载 作者:行者123 更新时间:2023-12-01 07:01:58 26 4
gpt4 key购买 nike

我有一个二维数组,我想将其转换为字符串示例

我想将 int[][] p 转换为 String,我使用 toString 但失败了。

int [][] p = new int[9][9];
for(int i = 0;i<9;i++) {
for(int j = 0;j<9;j++){
p[i][j] = 1;
}
}

String str="";
for(int i = 0; i< 9; i++) {
for(int j = 0; j< 9; j++)
{
str+=p[i][j].toString +" ";
}
}

最佳答案

您的代码无法编译,因为:

  1. 您正在尝试调用基元上的方法;
  2. 您在该方法调用中缺少括号。

这个:

str+=p[i][j].toString +" ";

应该是

str+=Integer.toString(p[i][j]) +" ";

或者,更简单:

    str+=p[i][j] +" ";

如果要在循环中构建字符串,则应避免连接,而使用 StringBuilder 代替:

StringBuilder sb = new StringBuilder();
for(int i = 0; i< 9; i++) {
for(int j = 0; j< 9; j++)
{
sb.append(p[i][j]);
sb.append(" ");
}
// You maybe want sb.append("\n") here, if you want it on separate lines.
}
String str = sb.toString();

当然,通常将二维数组转换为字符串的更简单方法是使用:

String str = Arrays.deepToString(p);

但这可能不是您想要的格式。

关于java - 将 int[][] 转换为 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43547355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com