Creating a program for a user to input the number of push ups they did in a session, displaying that session's number in one textview while showing the sum of all push up sessions in a second textview.
I tried the code below which seemed to work for a lot of people but I am getting the error "cannot resolve symbol i"
is there an issue with my code, or this method? Any tips on finding the sum of arraylist items in a date range would be much appreciated too
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Integer> pushuplist = new ArrayList<>();
EditText PushupEditText = findViewById(R.id.PushupEditText);
Button AddButton = (Button) findViewById(R.id.Submit);
AddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText PushupEditText = findViewById(R.id.PushupEditText);
TextView PushupTextView = findViewById(R.id.PushupTextView);
TextView TotalPushupsText = findViewById(R.id.TotalPushupsText);
int PushupNum = Integer.parseInt(PushupEditText.getText().toString());
pushuplist.add(PushupNum);
PushupTextView.setText(PushupNum+"");
int sum = 0;
for (int i = 0; i < pushuplist.size(); i++);
{
sum += pushuplist.get(i);
}
}
});
答案 0 :(得分:0)
删除最后一个分号:
for (int i = 0; i < pushuplist.size(); i++);
答案 1 :(得分:0)
下面的代码在for循环声明之后有一个多余的分号。删除该分号即可解决问题。
int sum = 0;
for(int i = 0; i < pushuplist.size(); i++); // remove this semicolon
{
sum += pushuplist.get(i);
}
如果您想知道为什么它不会触发编译器错误或警告,请继续阅读。
编写for循环时,如果不添加花括号,则下一个可执行语句将在该for循环的迭代中运行。
for(int i = 0; i < 10; i++) System.out.println(i);
for(int i = 0; i < 10; i++)
System.out.println(i);
这些都是有效代码的实例。在这两种情况下,打印都会被触发10次,并将打印出i
的值。
如果for循环声明后有分号(如您的分号):
for(int i = 0; i < pushuplist.size(); i++);
下一个可执行语句是分号;
,因此在所有for循环迭代中都不会运行任何内容。
希望这种解释应能使人们对那里发生的事情有所了解。
祝您的应用程序好运!
答案 2 :(得分:0)
您在for()中有一个小错误 请改用此代码。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<Integer> pushuplist = new ArrayList<>();
EditText PushupEditText = findViewById(R.id.PushupEditText);
Button AddButton = (Button) findViewById(R.id.Submit);
AddButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText PushupEditText = findViewById(R.id.PushupEditText);
TextView PushupTextView = findViewById(R.id.PushupTextView);
TextView TotalPushupsText = findViewById(R.id.TotalPushupsText);
int PushupNum = Integer.parseInt(PushupEditText.getText().toString());
pushuplist.add(PushupNum);
PushupTextView.setText(PushupNum+"");
int sum = 0;
for (int i = 0; i < pushuplist.size(); i++)
{
sum += pushuplist.get(i);
}
}
});