DivineChili DivineChili - 3 months ago 11
Java Question

Duplicate first index of array in java application

I am creating a little utility program. In this program I am trying to assign an array to a Java Object like so:

new Food( name, state, arrayOfSymptoms, comment, isCategory)
, where arrayOfSymptoms is the array I have problems with.

When I send the content of the array to output log,
[sym1, sym2, sym3, sym4]
.

However, after the construction is finished the array looks like this:
[sym1, sym1, sym2, sym3, sym4]


Does someone know an easy way to fix this problem, or do I have to create a lot of extra code to delete and move indexes?

Thank you in advance!

Edit:

Code before constructor:

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)
);
}


Creates the output shown here:

CurrSym(0): Name: Sym1, Comment: ""

CurrSym(1): Name: Sym2, Comment: ""

CurrSym(2): Name: Sym3, Comment: ""

CurrSym(3): Name: Sym4, Comment: ""

This clearly shows that the array only contains 4 elements.
However, when I convert the object into JSON, the output becomes as shown:
{"title": "Test Food", "state": 0, "symptoms":[{"name":"Sym1","comment":""},{"name":"Sym1","comment":""},{"name":"Sym2","comment":""},{"name":"Sym3","comment":""},{"name":"Sym4","comment":""}],"comment": "", "isCategory": false}


The code to convert the object to JSON looks like this:

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 + "}";
}


Hope this new information helps!

Answer

You are missing an 'else' in 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; 
}

``