gpt4 book ai didi

java - 如何生成随机数并将其导出为 JSON?

转载 作者:行者123 更新时间:2023-12-01 11:14:04 25 4
gpt4 key购买 nike

我计划生成一个随机数并使用 json-simple 将其导出为 JSON。我有以下代码

public class Main implements JSONAware{

private final int data;

public Main(int data){
this.data = data;
}


public String toJSONString(){
StringBuffer sb = new StringBuffer();

sb.append("[");

sb.append(data);

sb.append("]");
sb.append(",");


return sb.toString();
}

public static void main(String[] args){

JSONArray da = new JSONArray();


Random generator = new Random();
int [][] grid;

grid = new int[128][14];

for (int row = 0; row < 128; row++){
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
// da.add("%d",grid[row][col]);
da.add(grid[row][col]);
}
// System.out.println();
}
System.out.println(da);

}

打印如下:

[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7 ,91,...]

但我试图将其打印为

[9,62,6,60,29,28,59,56,67,61,53,23,22,31,15,96,94,85,65,94,15,7,91,...],
[68,48,40,44,47,85,8,43,17,78,35,7,77,26,80,34,19,47,17,0,59,5,79,...],
.
.
.

谁能告诉我如何将行与列分开?

最佳答案

据我了解您的问题,您希望 128 行是单独的 JsonArray,即 1 行 = 1 JsonArray。
为此,你可以这样做:

public static void main(String[] args){

JSONArray jArray = new JSONArray();

Random generator = new Random();
int [][] grid;

grid = new int[128][14];

for (int row = 0; row < 128; row++){
JSONArray da = new JSONArray();
for (int col = 0; col < 14; col++){
grid[row][col] = generator.nextInt(100);
da.add(grid[row][col]);
}
jArray.add(da);
}
System.out.println(jArray);

}

关于java - 如何生成随机数并将其导出为 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32042682/

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