簡體   English   中英

為什么我的應用程序停止工作?

[英]Why does my application stop working?

因此,我試圖做一個應用程序,該應用程序將獲得一個介於1和4之間的隨機數(包括1和4排除在外),然后獲得該數字,它將把我的主活動的背景色更改為相關的數字:

如果得到數字1:更改為藍色如果數字2:更改為黑色如果3:更改為黃色

這是代碼:

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

    Button button = (Button) findViewById(R.id.button);
    Button button2 = (Button) findViewById(R.id.button2);

    button.setOnClickListener( new  View.OnClickListener() {

            public void onClick(View v) {

            LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            Random rnd = new Random();
            int random = rnd.nextInt(1 - 4);

                if (random == 1) {

                layout.setBackgroundColor(Color.BLUE);

                } else if (random == 2) {

                layout.setBackgroundColor(Color.BLACK);

                } else {

                layout.setBackgroundColor(Color.YELLOW);

                }


            }
        }
    );
}

該代碼對我來說似乎很好,並且Android Studio不會報告任何錯誤(僅是由於button2而引起的警告),但是每次我點擊該按鈕時,應用程序都會關閉並顯示“不幸的是,運動已停止。”

我的問題是:為什么在點擊按鈕后應用程序會停止運行?

(如果需要更多信息,請告訴我。我從沒問過,我是Android和Android開發方面的新手)

rnd.nextInt(1 - 4); 計算為rnd.nextInt(-3); 由於參數為負,將拋出IllegalArgumentException

由於您自己沒有處理該異常,因此應用程序會發生不良情況。 要生成某個范圍內的隨機整數,請參見如何在Java中生成特定范圍內的隨機整數?

參考: https : //docs.oracle.com/javase/7/docs/api/java/util/Random.html#nextInt(int)

檢查您的logcat以獲取更多信息。

這行對我來說似乎很奇怪: rnd.nextInt(1 - 4);

這樣對嗎?

random.nextInt(int bound)方法接受bound參數,這是JDK中的方法:

public int nextInt(int bound) {
  if (bound <= 0)
    throw new IllegalArgumentException(BadBound);

  int r = next(31);
  int m = bound - 1;
  if ((bound & m) == 0)  // i.e., bound is a power of 2
    r = (int)((bound * (long)r) >> 31);
  else {
    for (int u = r;
      u - (r = u % bound) + m < 0;
      u = next(31))
      ;
  }
  return r;
}

因此,如果bound小於或等於0,則會引發異常,則界限為-3,從而導致該異常。 將綁定更改為random.nextInt(3) + 1

聲明以下內容: LinearLayout layout = (LinearLayout) findViewById(R.id.layout); 在onClick偵聽器的外面。

同時為您的1到4之間的隨機數生成器嘗試此操作

Random r = new Random();
int i1 = r.nextInt((4 - 1) + 1) + 1;
int random = rnd.nextInt(1 - 4); 

問題出在上面的那一行,因為它可能引發Exception。

嘗試使用try {} catch {}塊來捕獲此異常,您將看到。

您也可以更改算法,例如使用帶有顏色的列表

List<Color> colors = Arrays.asList(Color.BLUE, Color.RED, Color.YELLOW);
layout.setBackgroundColor(colors.get(rand.nextInt(colors.size() - 1));
int random = rnd.nextInt(4);

要么

int random = rnd.nextInt(3);

如Bathsheba所述,您對nextInt函數的邏輯不正確。

Oracle文檔中有關Random和nextInt(int n)的詳細說明 ,nextInt函數“返回偽隨機數,其int值均勻地分布在0(包含)和指定值(不含)之間”。

因此,您嘗試生成0到-3之間的數字,這會導致“ IllegalArgumentException錯誤”,因為'n'不是正數。

以下是生成介於1(含)和4(不含)之間的隨機數的一種正確方法:

int random = rnd.nextInt(3) + 1
  • 'rnd.nextInt(2)'將生成0、1或2
  • 在這些選項上加1可得到所需的1、2或3輸出

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM