2016-06-05 6 views
0

Summieren Elemente einer Array-Liste direkt nach dem Hinzufügen eines neuen Elements in Net-Beans verursacht das erste Element hinzugefügt, um nicht in der Summe gezählt werden.Dann wenn ich ein anderes hinzufügen Element es summiert nur das zweite Element added.Code ist unten und es gibt ein Bild von meinem Problem.Summieren Elemente in einer Array-Liste nach dem Hinzufügen eines neuen Elements in Net-Beans

https://gyazo.com/12f13ab5724af3de8d9848994987910d

private void balanceAddActionPerformed(java.awt.event.ActionEvent evt) { 
    try { 
     outputBox.setText(""); 
     String check = addInput.getText(); 
     int check1 = check.length(); 
     if ("".equals(check)) { 
      errorLabel.setText("Nothing has been entered to be added."); 
      for (int i = 0; i < balance.size(); i++) { 
       outputBox.setText(outputBox.getText() + balance.get(i) + "\n"); 
      } 
     } else if (check1 >= 7) { 
      errorLabel.setText("Too many characters limit your characters to 7"); 
      addInput.setText(""); 
      for (int i = 0; i < balance.size(); i++) { 
       outputBox.setText(outputBox.getText() + balance.get(i) + "\n"); 
      } 
     } else { 
      double list = Integer.parseInt(addInput.getText()); 
      balance.add(list); 
      addInput.setText(""); 
      //Setting the array list in outputbox 
      for (double i = 0; i < balance.size(); i++) { 
       outputBox.setText(outputBox.getText() + balance.get((int) i) + "\n"); 
       errorLabel.setText(""); 
       double sum = 0; 
       for (double j = 1; j < balance.size(); j++) { 
        sum += balance.get((int) j); 

        String converted = String.valueOf(sum); 
        errorLabel.setText("Your sum is " + (converted)); 
       } 
      } 
     } 
    } catch (Exception e) { 
     errorLabel.setText("Error wrong characters."); 
     for (int i = 0; i < balance.size(); i++) { 
      outputBox.setText(outputBox.getText() + balance.get(i) + "\n"); 
     } 
    } 
} 
+0

Indizes bei 0 in Java zu starten, nicht 1. Und eine for-Schleife sollte eine int-Variable verwenden, nicht ein double: 'für (int j = 0; j

Antwort

1

Das Hauptproblem ist, dass Sie Ihre Summenschleife bei 1 beginnen, weshalb der erste Index 0 gets übersprungen:

for(int j=0; j<balance.size(); j++){ 
    sum += balance.get(j);  
} 
String converted = String.valueOf(sum); 
errorLabel.setText("Your sum is " + (converted)); 

Andere Randnoten:

  • Es ist nicht erforderlich,zu deklarieren 0 als double (und dann zurück auf int)
  • Es besteht keine Notwendigkeit, das Etikett innerhalb der Schleife zu aktualisieren. Sie können es tun, sobald die Schleife fertig ist, die Summe zu berechnen.
  • Um das Ganze sauberer zu machen, können Sie eine for-each Schleife verwenden können, da man den Index nicht benötigen (und weil ArrayList ist iterable)

    for(double b: balance){ 
        sum += b;  
    } 
    
+0

Vielen Dank. – Franklin

Verwandte Themen