简体   繁体   English

如何在 java 中操作数组

[英]How to manipulate an array in java

im making a blackjack game in java and I get an initial array of size two.我在 java 中制作二十一点游戏,我得到一个大小为 2 的初始数组。 However when I want to twist I want to add another card to the array.但是,当我想扭转时,我想将另一张卡添加到阵列中。 However I cannot change its size但是我不能改变它的大小

 public static void userDrawCards() {
        int min = 1;
        int max = 11;

        int[] cards = new int[2];

        System.out.println("Welcome to BlackJack");

        for (int i = 0; i < cards.length; i++) {
            int random = (int) (Math.random() * (max - min + 1) + min);
            cards[i] = random;
        }
        System.out.println("Your cards are " + Arrays.toString(cards));
    }

Ive checked and it says an arraylist would be better to use.我检查过,它说 arraylist 会更好用。 So i try this and im unsure on how to use it when i try i get this所以我试试这个,当我尝试得到这个时我不确定如何使用它

public static void userDrawCards() {
        int min = 1;
        int max = 11;

        List cards = new ArrayList();

        System.out.println("Welcome to BlackJack");

        for (int i = 0; i < cards.size(); i++) {
            int random = (int) (Math.random() * (max - min + 1) + min);
            cards.set(i, random);
        }
        System.out.println("Your cards are " + cards);
    }

Giving me this Your cards are [] as a response.给我这个你的卡片是 [] 作为回应。 Any help would be great thanks:)任何帮助都会非常感谢:)

first of all, it's a good practice to add parameter of type you are going to use in your list.首先,在列表中添加要使用的类型参数是一个好习惯。 In your case cards are ints so use:在您的情况下,卡片是整数,因此请使用:

    List<Integer> cards = new ArrayList<Integer>();

this creates an empty list, so it's size is 0. That means your for loop is completely skipped.这将创建一个空列表,因此它的大小为 0。这意味着您的 for 循环被完全跳过。 To fix that declare some variable of how many cards you want to have:要解决这个问题,请声明您想要拥有多少张卡片的一些变量:

final int amountOfCards = 10;
List<Integer> cards = new ArrayList<>(amountOfCards); // argument is optional, this is just for efficiency purposes

Now you can have for loop like this:现在你可以有这样的 for 循环:

for (int i = 0; i <amountOfCards; i++) {

but you can't use set at this point.但此时您不能使用 set 。 The list is empty, so if you use set, you are going to get IndexOutOfBoundsException.列表是空的,所以如果你使用 set,你会得到 IndexOutOfBoundsException。 If you want to add cards, use add :如果要添加卡片,请使用add

cards.add(random);

alternatively you can add at position using cards.add([index here], random)或者,您可以使用cards.add([index here], random)在 position 添加

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM