问题
In my activity, there are two buttons: one for adding an item to a ListView, which is formed by an EditText (where the user enters a decimal number) and another one, which will start the calculation. The goal is to calculate the average of the numbers entered in the EditTexts, depending on the number of items added to the ListView.
I have the following code, and I think I might get the number of childs created and then divide the adding by the childs, but I have read a lot of similar examples and I have no idea how to do that.
Here is the code:
void addNumberFromText()
{
double total=0;
for(int i=0;i<MarkListView.getChildCount();i++)
{
View wantedView = MarkListView.getChildAt(i);
markresult = (TextView)wantedView.findViewById(R.id.subjectmark);
double value=Double.parseDouble(markresult.getText().toString());
total+=value;
}
markresult1 = (TextView)findViewById(R.id.average);
markresult1.setText(Double.toString(total));
markresult1.setText(String.format("%.2f", total));
}
I appreciate the help, thank you!
回答1:
I have the solution! I added: averagevalue=total/MarkListView.getChildCount(); which is the number of childs.
void addNumberFromText()
{
double total=0;
double averagevalue=0;
for(int i=0;i<MarkListView.getChildCount();i++)
{
View wantedView = MarkListView.getChildAt(i);
markresult = (TextView)wantedView.findViewById(R.id.subjectmark);
double value=Double.parseDouble(markresult.getText().toString());
total+=value;
averagevalue=total/MarkListView.getChildCount();
}
markresult1 = (TextView)findViewById(R.id.average);
markresult1.setText(Double.toString(averagevalue));
markresult1.setText(String.format("%.2f", averagevalue));
Thanks for the responses, all were similar and correct. Thank you!
回答2:
From your code, it seems that you haven't calculated the average like you say. You calculated the total but forgot to calculate the average by dividing the total by your total list items. Hope it helps.
来源:https://stackoverflow.com/questions/25463273/average-from-edittexts