-1

我正在尝试制作一个检查一年中日期的应用程序。每当我声明一个大于某个数字的数组时,我都会收到停止响应消息。我应该怎么办?

 public class Main extends Activity {

int[] payDays = new int[11];
int dayOfYear;
Calendar cal;

Intent goToSales, goToChains, goToCheck, goToReference;

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


    cal = Calendar.getInstance();
    dayOfYear = cal.get(Calendar.DAY_OF_YEAR);

    payDays = new int[11];

    payDays[0] = 60;
    payDays[1] = 88;
    payDays[2] = 123;
    payDays[3] = 151;
    payDays[4] = 179;
    payDays[5] = 214;
    payDays[6] = 242;
    payDays[7] = 270;
    payDays[8] = 305;
    payDays[9] = 333;
    payDays[10] = 361;
    payDays[11] = 31;

    // Phew! Checks when to send the notification
    if (dayOfYear == payDays[0] || 
        dayOfYear == payDays[1] ||
        dayOfYear == payDays[2] ||
        dayOfYear == payDays[3] ||
        dayOfYear == payDays[4] ||
        dayOfYear == payDays[5] ||
        dayOfYear == payDays[6] ||
        dayOfYear == payDays[7] ||
        dayOfYear == payDays[8] ||
        dayOfYear == payDays[9] ||
        dayOfYear == payDays[10] ||
        dayOfYear == payDays[11]) 
    {


        Notification noti = new Notification.Builder(this)
        .setContentTitle("MCHelper")
        .setContentText("It's the end of the year!")
        .setSmallIcon(R.drawable.notify2).build();
        noti.flags |= Notification.FLAG_AUTO_CANCEL;


        NotificationManager notiMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
          notiMan.notify(0, noti);

          Context context = getApplicationContext();
          CharSequence text = "Hello toast!";
          int duration = Toast.LENGTH_SHORT;

          Toast toast = Toast.makeText(context, text, duration);
          toast.show();   
    }
4

3 回答 3

4

看这个:

int[] payDays = new int[11];

现在您正在尝试访问索引 11:

payDays[11] = 31;

那是行不通的。当您使用new int[size](或任何其他类型的数组,当然)创建包含size元素的数组时,从 0 到size 独占

我怀疑你想要:

int[] payDays = new int[12];

(此外,我会使用循环来检查数组是否包含特定值,或者更改排序以使其有序,然后使用Arrays.binarySearch.)

于 2013-02-21T08:40:58.873 回答
1

您正在声明您的数组错误。而不是payDays = new int[11];你想要的payDays = new int[12];,否则,你最终会访问元素 11,它超出了界限,你会得到一个错误。

于 2013-02-21T08:40:43.197 回答
1

数组索引从零开始。当您声明一个大小为 11的数组时,将创建一个索引范围从 0 到 10(共 11 个元素)的数组元素。因此访问 payDays[11] 将引发 ArrayIndexOutOfBounds 异常。

解决方案可能是

1) 增加数组的大小为payDays = new int[12]

2)移除元素payDays[11] = 31;

于 2013-02-22T08:53:06.567 回答