Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 我的嵌套For循环不工作_Java_For Loop_Nested Loops - Fatal编程技术网

Java 我的嵌套For循环不工作

Java 我的嵌套For循环不工作,java,for-loop,nested-loops,Java,For Loop,Nested Loops,因此,我正在为一个for循环不起作用的纸牌游戏创建一个牌组构造函数。这是它的代码,忽略构造函数中的第三个整数变量,因为它不能解决问题,所以我将其注释掉: public Deck(String[] ranks, String[] suits, int[] values) { cards = new ArrayList<Card>(); for(int a = 0; a<=ranks.length; a++){ for(int b=0; b&

因此,我正在为一个for循环不起作用的纸牌游戏创建一个牌组构造函数。这是它的代码,忽略构造函数中的第三个整数变量,因为它不能解决问题,所以我将其注释掉:

public Deck(String[] ranks, String[] suits, int[] values) {
    cards = new ArrayList<Card>();
    for(int a = 0; a<=ranks.length; a++){
            for(int b=0; b<=suits.length;b++){
                cards.add(new Card(ranks[a],suits[b], 0));
                System.out.println(cards);
                size+=1;
            }
        }
    }

任何帮助都将不胜感激,谢谢您抽出时间

n个元素的数组的索引范围为
0
n-1
n
对于这样的数组是无效的索引

你的指数下降了一。应该是:

for(int a = 0; a<ranks.length; a++){
        for(int b=0; b<suits.length;b++){
            cards.add(new Card(ranks[a],suits[b], 0));
            System.out.println(cards);
            size+=1;
        }
    }
}

for(int a=0;an个元素的数组具有从
0
n-1
n
的索引对于此类数组无效

你的指数相差一。它应该是:

for(int a = 0; a<ranks.length; a++){
        for(int b=0; b<suits.length;b++){
            cards.add(new Card(ranks[a],suits[b], 0));
            System.out.println(cards);
            size+=1;
        }
    }
}

for(int a=0;a如果不需要数组索引,可以使用for-each循环

它使你免于犯这种错误

for(String ra : ranks){
        for(Stirng su : suits){
            cards.add(new Card(ra, su, 0));
            System.out.println(cards);
            size+=1;
        }
    }
}

它很容易阅读,但不能在所有情况下都使用。

如果不需要数组索引,可以使用for-each循环

它使你免于犯这种错误

for(String ra : ranks){
        for(Stirng su : suits){
            cards.add(new Card(ra, su, 0));
            System.out.println(cards);
            size+=1;
        }
    }
}

它很容易阅读,但你不能在任何情况下都使用。

该死,你打败了我!对于OP:Length提供了数组的长度(即4个元素),但是这些元素是零索引的,即0、1、2、3。该死,你打败了我!对于OP:Length提供了数组的长度(即4个元素),但这些元素的索引为零,即0、1、2、3。另请参见