0

到目前为止,我有以下 java 代码。我是java新手。我希望最大计数为 500,之后计数返回“0”,您可以再次开始计数。

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class wazeefa extends Activity
{
    TextView txtCount;
    Button btnCount;
    int count = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.wazeefa);

        //button sound
        final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.countbutton);

        txtCount = (TextView)findViewById(R.id.wcount);
        txtCount.setText(String.valueOf(count));
        btnCount = (Button)findViewById(R.id.wclick);

        btnCount.setOnClickListener(new OnClickListener()
        {
            public void onClick(View V)
            {
                count++;
                txtCount.setText(String.valueOf(count));
                mpButtonClick.start();
            }
        });
    }
}
4

3 回答 3

2

使用 %(模数/提醒)运算符。

count = (count + 1) % 500; //count will be in range [0,499] inclusive

或者,如果您也想允许 500:

count = (count + 1) % 501; //count will be in range [0,500] inclusive
于 2012-12-19T13:48:02.767 回答
1
if(count > 500) {
    count = 0;
}

这是 if 语句,基本上括号内的代码只有在顶部所说的内容为真时才会执行。它是编程的基础,如果你是 Java 新手,你的代码还不错

于 2012-12-19T13:48:15.703 回答
1
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.EditText;

public class wazeefa extends Activity{

TextView txtCount;
Button btnCount;
int count = 0;  

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.wazeefa);

    //button sound
    final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.countbutton);

    txtCount = (TextView)findViewById(R.id.wcount); 
    txtCount.setText(String.valueOf(count));
    btnCount = (Button)findViewById(R.id.wclick);       

    btnCount.setOnClickListener(new OnClickListener() {
         public void onClick(View V) {
            count++; 
            txtCount.setText(String.valueOf(count));
            mpButtonClick.start();

            if (count >= 500) {
               count = 0;
            }
        }
        });
}}
于 2012-12-19T13:49:35.043 回答