简体   繁体   中英

Random Number Generator crashes

I'm making a random number generator for android and I'm new to Java. With some help, I managed to make something that should work but when I try to launch it in an emulator the app crashes. Here is the code I used:

public class MainActivity extends AppCompatActivity implements OnClickListener {

EditText RndNbGenNbs1, RndNbGenNbs2;
TextView RndNbGenResult;

int MinNumber;
int MaxNumber;
String Result;
Random Rnd = new Random();
String Number1;
String Number2;
Button btn;

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

    RndNbGenNbs1 = (EditText) findViewById(R.id.RndNbGenNbs1);
    RndNbGenNbs2 = (EditText) findViewById(R.id.RndNbGenNbs2);
    RndNbGenResult = (TextView) findViewById(R.id.RndNbGenResult);
    Number1 = RndNbGenNbs1.getText().toString();
    Number2 = RndNbGenNbs2.getText().toString();
    btn = (Button) findViewById(R.id.RndNbGenBtn1);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.RndNbGenBtn1:

            MinNumber = Integer.parseInt(Number1);
            MaxNumber = Integer.parseInt(Number2);

            Rnd.nextInt(MaxNumber - MinNumber);

            Result = Rnd.toString();

            RndNbGenResult.setText(Result);
            break;


    }

}

}

From your Log:

ComponentInfo{com.jeepingviini.randomnumbergenerator/com.jeepingviini.randomnumbergenerator.MainActivity}: java.lang.ClassCastException: android.support.v7.widget.AppCompatTextView cannot be cast to android.widget.EditText

You're trying to cast an AppCompatTextView to EditText .

Check RndNbGenNbs1 , RndNbGenNbs2 and RndNbGenResult , one (or all) of them is declared as AppCompatTextView in xml file, while you're tryin to cast it as EditText in your java code.

You need to choose if you want an EditText or AppCompatTextView .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM