我正在爲android創建一個隨機數生成器,而我是Java新手。有了一些幫助,我設法做出了一些應該可以工作的東西,但是當我嘗試在模擬器中啓動應用程序時,它會崩潰。下面是我使用的代碼:隨機數發生器崩潰
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;
}
}
}
'String Number1 = RndNbGenNbs1.getText()。toString();''和'String Number2 = RndNbGenNbs2.getText()。toString();'在您的代碼的初始化塊中。因爲'RndNbGenNbs1'和'RndNbGenNbs2'在調用onCreate()之前沒有設置,所以它應該拋出一個'NullPointerException'並且崩潰。嘗試調試,而不是簡單地運行您的項目。 – GiantTree
如果這裏有幫助的是LogCat日誌http://pastebin.com/tUuBH6qW – jeepingviini