[英]Index 12 out of bounds for length 12. How can I fix this problem?
Everytime I run the code I get an Index 12 out of bounds for length 12. I'm not sure what is the problem.每次运行代码时,我都会得到长度为 12 的索引 12 超出范围。我不确定是什么问题。 Here is the code:这是代码:
enter code here: int getDayNumber(int day,int month,int year) {
if(this.leapYear(year)) {
int months[] = {31,29,31,30,31,30,31,31,30,31,30,31};
int cnt = 0 ;
for(int i=0;i<month-1;i++) {
cnt += months[i];
System.out.println(cnt + " " + i);
}
return cnt + day ; // count = cnt
The (month - 1) that you've used inside the loop points to the month passed in the parameter in the function getDayNumber.您在循环中使用的 (month - 1) 指向 function getDayNumber 中的参数中传递的月份。 Consider using.length function to calculate the length of the array.考虑使用.length function 来计算数组的长度。 Try using for loop something like:尝试使用 for 循环,例如:
for(int i = 0 ; i < months.length ; i++)
Your concept of how Array works is pretty clear.您对 Array 如何工作的概念非常清楚。 Just use months.length and you're good to go.只需使用months.length,您就可以开始了。 Tell me how this works out for you!告诉我这对你有什么影响!
package projectlearn1;
public class ArrayQueue {
private int[] mArray;
private int mCount;
public ArrayQueue(int sz) {
mArray=new int[sz];
mCount=0;
}
public void add(int val){
mArray[mCount++]=val;
}
public int front(){
return mArray[0];
}
public int pop(){
int ret=mArray[0];
mCount--;
for (int i = 0; i < mCount; i++) {
mArray[i-1]=mArray[i];
}
return ret;
}
public int size(){
return mCount;
}
public boolean isEmpty(){
return size()==0;
}
public static void main(String[] args) {
int tmp=0;
ArrayQueue astack=new ArrayQueue(12);
astack.add(10);
astack.add(20);
astack.add(30);
tmp=astack.pop();
System.out.printf("tmp=%d\n",tmp);
tmp=astack.front();
System.out.printf("tmp=%d\n",tmp);
astack.add(40);
System.out.printf("isEmpty()=%b\n",astack.isEmpty());
System.out.printf("size()=%d\n",astack.size());
while (!astack.isEmpty()){
System.out.printf("size()=%d\n",astack.pop());
}
}
}
import java.util.*;导入 java.util.*; public class BinaryTreessssB {公共 class BinaryTreessssB {
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
static class BinaryTree{
static int idx = -1;
public static Node buildTree(int nodes[]){
idx++;
if (nodes[idx] == -1){
return null;
}
Node newNode = new Node(nodes[idx]);
newNode.left = buildTree(nodes);
newNode.right = buildTree(nodes);
return newNode;
}
public static void preorder(Node root){
if (root == null){
}
System.out.println(root.data+" ");
preorder(root.left);
preorder(root.right);
}
}
public static void main(String[] args) {
int nodes[] = {1, 2, 4, -1, 5, -1, -1, 3, -1, 6, -1, -1};
BinaryTree tree = new BinaryTree();
Node root = tree.buildTree(nodes);
tree.preorder(root);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.