我正在创建一个小实用程序。在这个程序中,我试图将一个数组分配给Java对象,如下所示:
new Food( name, state, arrayOfSymptoms, comment, isCategory)
,其中arrayOfSymptoms是我遇到问题的数组。
当我将数组的内容发送到输出日志[sym1, sym2, sym3, sym4]
时
但是,构建完成后,数组如下所示:[sym1, sym1, sym2, sym3, sym4]
有人知道解决此问题的简单方法,还是需要创建大量额外代码来删除和移动索引?
提前谢谢!
编辑:
构造函数之前的代码:
Symptoms[] allSyms = new Symptoms[selSyms.size()];
for (int j = 0; j < selSyms.size(); j++) {
allSyms[j] = selSyms.get(j);
System.out.println("CurrSym(" + j + "): " + allSyms[j]);
}
System.out.println("Amount of symptoms selected: " + allSyms.length);
if( // Basic Form Validation
!nameField.getText().isEmpty()) {
if (!isCategory.isSelected())
MainController.makeLeaf(
MainController.categoryTitles.indexOf(categories.getValue()),
new Food(
nameField.getText(),
stateChoice.getSelectionModel().getSelectedIndex(),
allSyms, // Symptoms Here
"",
false)
);
}
创建此处显示的输出:
CurrSym(0):姓名:Sym1,评论:&#34;&#34;
CurrSym(1):姓名:Sym2,评论:&#34;&#34;
CurrSym(2):姓名:Sym3,评论:&#34;&#34;
CurrSym(3):姓名:Sym4,评论:&#34;&#34;
这清楚地表明该阵列只包含4个元素。
但是,当我将对象转换为JSON时,输出如下所示:
{"title": "Test Food", "state": 0, "symptoms":[{"name":"Sym1","comment":""},{"name":"Sym1","comment":""},{"name":"Sym2","comment":""},{"name":"Sym3","comment":""},{"name":"Sym4","comment":""}],"comment": "", "isCategory": false}
将对象转换为JSON的代码如下所示:
public String symptomsToJSON()
{
String allSymptoms = "";
if(getSymptoms() != null)
{
for (int i = 0; i < symptoms.length; i++) {
if (i == 0)
allSymptoms += symptoms[i].toJSON();
allSymptoms += "," + symptoms[i].toJSON();
}
}
return allSymptoms;
}
public String toJSON()
{
return "{\"title\": \"" + title + "\", \"state\": "+ state + ", \"symptoms\":[" + symptomsToJSON() + "],\"comment\": \"" + comment +"\", \"isCategory\": " + isCategory + "}";
}
希望这些新信息有所帮助!
答案 0 :(得分:0)
你错过了一个&#39;否则&#39;在symptomsToJSON()中:
public String symptomsToJSON() {
String allSymptoms = "";
if(getSymptoms() != null) {
for (int i = 0; i < symptoms.length; i++) {
if (i == 0)
allSymptoms += symptoms[i].toJSON();
//NOTE: Without this, the preceding line gets printed twice for i==0
else
allSymptoms += "," + symptoms[i].toJSON();
}
}
return allSymptoms;
}
``