2016-10-14 6 views
0

これは乱数ジェネレータのJavaファイルです。私はアプリを実行するたびにクラッシュする。私を助けてください!アプリがクラッシュしている - 乱数ジェネレータ

public class MainActivity extends AppCompatActivity { 

    int k; 

    public void lol(View v) { 

     EditText e1 = (EditText) findViewById(R.id.e1); 
     EditText e2 = (EditText) findViewById(R.id.e2); 
     TextView t = (TextView) findViewById(R.id.t); 
     int h = Integer.parseInt(String.valueOf(e1)); 
     int i = Integer.parseInt(String.valueOf(e2)); 
     Random u = new Random(); 

     k = h + u.nextInt(i); 
     t.setText(k); 
    } 
} 
+2

エラーは何ですか? –

+0

スタックトレースを転記してください。 –

+0

より具体的にする必要があります。ログを投稿してください。 – EJoshuaS

答えて

2

EditTextからテキストを取得する必要があります。また、文字列を解析する際にtry catchブロックを使用する必要があります。そうでなければ、文字列をintに解析できない場合はRuntimeExceptionをスローする可能性があります。

public void lol(View v) { 

    EditText e1 = (EditText) findViewById(R.id.e1); 
    EditText e2 = (EditText) findViewById(R.id.e2); 
    TextView t = (TextView) findViewById(R.id.t); 
    String e1Text = e1.getText().toString(); 
    String e2Text = e2.getText().toString(); 
    try{ 
     int h = Integer.parseInt(String.valueOf(e1)); 
     int i=Integer.parseInt(String.valueOf(e2)); 
     Random u = new Random(); 


     k = h + u.nextInt(i); 
     t.setText(k); 
    }catch(Exception e){ 
     //some exception 
    } 
} 
+0

thnks ...それは働いた................ – nesbak203

+0

@ nesbak203そして、これを受け入れられた答えとして確認してsanjeetに感謝します。 – pjs

0

このエラーはおそらく乱数が0(ゼロ)未満です。あなたがまた、のような何かを試みることができるこの

Random rn = new Random(); 
int range = maximum - minimum + 1; 
int randomNum = rn.nextInt(range) + minimum; 
+0

ありがとうございました........................................... – nesbak203

+0

おそらくOPが意図したものではないかもしれませんが、それでも有効な文字列が得られます。例外が発生するとは思わないでしょう。 – EJoshuaS

+0

@ nesbak203はあなたの問題を解決しましたか? –

0

のような範囲で乱数を生成することをお勧めします(これは、C#だ、ではないJavaのように、これはAndroid用Xamarinであることに注意してください)以下:

public void lol(View v) 
    { 
     EditText e1 = (EditText)FindViewById(Resource.Id.e1); 
     EditText e2 = (EditText)FindViewById(Resource.Id.e2); 
     TextView t = (TextView)FindViewById(Resource.Id.t); 

     int h, i, k; 

     // TryParse tries to parse the text as an integer and returns a value 
     // indicating whether or not it succeeded 
     // e1.Text is equivalent to a call to e1.getText() 
     if (int.TryParse(e1.Text, out h) && int.TryParse(e2.Text, out i)) 
     { 
      Random u = new Random(); 

      k = h + u.Next(i); 
      // This is equivalent to doing a call to t.setText(...) 
      t.Text = k.ToString(); 
     } 
    } 

をので、基本的には、使用しようとする前に実際にであることを確認してください。また、これはEditTextからテキストの値を取得するより良い方法です。

関連する問題