嵌套for循环java扑克游戏arraylist构造函数

时间:2016-11-13 10:17:45

标签: java arraylist

到目前为止,这是我的构造函数,一张45张牌,我写了一个基本的构造函数,应该制作一套45张卡片,其中套装的价值就像(0-spades,1-hearts,2-clubs) ,3颗钻石,4个制造商名称)和卡片值(1-9,其中1是王牌)

私人ArrayList卡;

public Deck() {
    cards = new ArrayList <Card>();

    for (int valueKind = 1; valueKind<9; valueKind++){ 
        Card newCard = new Card(valueKind,0); 
        cards.add(newCard); 
    }
    for (int valueKind = 1; valueKind<9; valueKind++){ 
        Card newCard = new Card(valueKind,1); 
        cards.add(newCard); 
    }
    for (int valueKind = 1 ; valueKind<9; valueKind++){ 
        Card newCard = new Card(valueKind,2); 
        cards.add(newCard); 
    } 
    for (int valueKind = 1; valueKind<9; valueKind++){ 
        Card newCard = new Card(valueKind,3); 
        cards.add(newCard); 
    } 
    for (int valueKind = 1; valueKind<9; valueKind++){ 
        Card newCard = new Card(valueKind,4); 
        cards.add(newCard); 
    } 

错误/缺失了什么?

2 个答案:

答案 0 :(得分:0)

如果要创建值1 - 9,则for循环处于错误状态。它应该是<= 9

我对您的代码进行了改进,因此它更清晰并修复了错误<= 9

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hendrawd on 11/13/16.
 */
public class Deck {
    List<Card> cards;

    public Deck() {
        cards = new ArrayList<>();
        makeCards(Card.SPADE);
        makeCards(Card.HEART);
        makeCards(Card.CLUB);
        makeCards(Card.DIAMOND);
        makeCards(Card.MADEUPNAME);
    }

    private void makeCards(int type) {
        for (int valueKind = 1; valueKind <= 9; valueKind++) {
            Card newCard = new Card(valueKind, type);
            cards.add(newCard);
        }
    }
}

class Card {
    static final int SPADE = 0;
    static final int HEART = 1;
    static final int CLUB = 2;
    static final int DIAMOND = 3;
    static final int MADEUPNAME = 4;

    private int value, type;

    Card(int value, int type) {
        this.value = value;
        this.type = type;
    }
}

答案 1 :(得分:0)

既然你没有给我一个明确的问题,我会给你一些关于代码的一般性建议。

首先,您当前的for循环从1循环到8循环,而不是1到9.您应该将循环条件从$payload = '{"aps":{"alert":"' . $message . '","sound":"default"}}'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'Certificate.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); stream_context_set_option($ctx, 'ssl', 'cafile', 'entrust_2048_ca.cer'); $fp = stream_socket_client('ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); $msg = chr(0) . pack('n', 32) . pack('H*', $item) . pack('n', strlen($payload)) . $payload; $result = fwrite($fp, $msg, strlen($msg)); fclose($fp); 更改为gen id= 1 if (char[_n-1] >= char[_n]) | _n ==1 replace id = sum(id) if id==1 replace id = id[_n-1] if missing(id) fillin id char drop _fillin

其次,您可以使用嵌套for循环缩短代码:

valueKind < 9

另一件事是,如果您使用常量,我认为您的代码将更具描述性:

valueKind <= 9