引用输入:(

时间:2014-03-19 03:38:07

标签: android random generator

我想知道是否有人可以告诉我如何使用我的输入/ EditText作为此随机数生成器的最大值(第15行,其中.nextInt(1000))的值。我已经尝试过如何做到这一点并问道。非常感谢任何帮助!

import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textOne = (TextView) findViewById(R.id.textView1);
    Button pushMe = (Button) findViewById(R.id.button1);
    pushMe.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String randText = "";
            // TODO Auto-generated method stub
            Random randGen = new Random();
            int rando = randGen.nextInt(1000) + 1;
            randText = Integer.toString(rando);
            textOne.setText(randText);
        }
    });
}

1 个答案:

答案 0 :(得分:0)

如果您的布局中有android:id="@+id/editText1"的EditText,那么这将是一种方式:

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final TextView textOne = (TextView) findViewById(R.id.textView1);
    final EditText editText = (EditText) findViewById(R.id.editText1);

    Button pushMe = (Button) findViewById(R.id.button1);        
    pushMe.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Random randGen = new Random();
                String randText = "";
                int max = 0;

                String input = editText.getText().toString();

                try
                {
                    max = Integer.parseInt(input);
                    int rando = randGen.nextInt(max) + 1;
                    randText = Integer.toString(rando);
                }
                catch (IllegalArgumentException e)
                {
                    randText = "Invalid input";
                }

                textOne.setText(randText);
            }
        }
    ); 
}

请注意,catch (IllegalArgumentException e)会同时抓住IllegalArgumentException可以投掷的Random.nextInt()以及NumberFormatException可以投掷的Integer.parseInt()