我正在尝试制作一款可以检查一年中某一天的应用。每当我声明一个大于某个数字的数组时,我都会得到一个Stops响应消息。我该怎么办?
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();
}
答案 0 :(得分:4)
看看这个:
int[] payDays = new int[11];
现在您正尝试访问索引11:
payDays[11] = 31;
那不行。当您使用new int[size]
(或任何其他类型的数组)创建包含size
元素的数组时,从0开始到size
独占。< / p>
我怀疑你想要:
int[] payDays = new int[12];
(另外,我要么使用循环来检查数组是否包含特定值,或者更改顺序以使其按顺序排列,并使用Arrays.binarySearch
。)
答案 1 :(得分:1)
您声明您的阵列错误。而不是payDays = new int[11];
你想要的payDays = new int[12];
否则,你最终会访问超出界限的元素11并且你会收到错误。
答案 2 :(得分:1)
数组索引从零开始。当您声明一个大小为11的数组时,将创建索引范围为0到10(总共11个元素)的数组元素 .Hence访问payDays [11] ]会抛出一个ArrayIndexOutOfBounds异常。
解决方案可能是
1)增加数组的大小 payDays = new int [12] ;
2)删除元素payDays [11] = 31;