簡體   English   中英

了解Java中的數組

[英]Understanding arrays in java

我正在讀一本關於Java的書,並在“數組”下給出了此示例。

public class Deck {
    public static void main(String[] args) {
        String[] suit = { "Clubs", "Diamonds", "Hearts", "Spades" };
        String[] rank = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };

        // avoid hardwired constants
        int SUITS = suit.length;
        int RANKS = rank.length;
        int N = SUITS * RANKS;

        // initialize deck
        String[] deck = new String[N];
        for (int i = 0; i < RANKS; i++) {
            for (int j = 0; j < SUITS; j++) {
                deck[SUITS*i + j] = rank[i] + " of " + suit[j];
            }
        }

        // shuffles our deck of cards
        for (int i = 0; i < N; i++) {
            int r = i + (int) (Math.random() * (N-i));
            String t = deck[r];
            deck[r] = deck[i];
            deck[i] = t;
        }

        // print shuffled deck
        for (int i = 0; i < N; i++) {
            System.out.println(deck[i]);
        }
    }

}

我想知道為什么使用“ int r = i +(int)(Math.random()*(Ni)); ”來洗牌嗎? 請說明此行的處理方式,以及為何明確使用此行(使用此行的邏輯)

Math.random()返回一個介於0.0和1.0之間的隨機double精度數,當此數字乘以Ni我們會得到一個介於兩個數字之差范圍內的數字(雙精度數): [0,Ni]

通過添加i我們將范圍從[0,Ni]移至[i,N]並且由於它是雙精度型,因此我們將其intint以便接收整數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM