首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有可能以这种方式进行洗牌,而不是使用布尔值而不是列表?

是否有可能以这种方式进行洗牌,而不是使用布尔值而不是列表?
EN

Stack Overflow用户
提问于 2021-12-17 15:22:20
回答 1查看 71关注 0票数 0

在这里,我的代码(用Java在Eclipse上)显示了文件中的3张随机卡片。我试图得到一个洗牌按钮工作和随机洗牌在3个新的卡片。我使用了“Collections.shuffle(卡片)”,并将它传递给我的布尔数组,但是它说我不能,因为它需要一个List<>列表。是否有可能让洗牌与我的布尔值一起工作,还是我必须使用列表?

这是我的代码:

代码语言:javascript
复制
import java.util.Collections;
import java.util.List;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class DisplayCards extends Application {
    
    HBox imageViews;

    
    @Override
    public void start(Stage primaryStage) throws Exception {
        GridPane pane = new GridPane();
        pane.setAlignment(Pos.CENTER);
        boolean[] cards = new boolean[52];
        int count = 0;
        while(count <3) {
            int card = (int)(Math.random() * 52);
            
            if(!cards[card]) {
                cards[card] = true;
                pane.add(new ImageView(new Image("card/" + (card) + ".png")), count, 0);
                count++;
            }
        }
        imageViews = new HBox();
        imageViews.setAlignment(Pos.CENTER);
        
        shuffle();
    
        
        Button btnShuffle = new Button("Shuffle");
        btnShuffle.setOnAction(new EventHandler<ActionEvent>() {
            
            public void handle(ActionEvent event) {
                shuffle();
                
            }
        });
        
        BorderPane Bpane = new BorderPane();
        Bpane.setCenter(imageViews);
        Bpane.setBottom(btnShuffle);
        
        Scene scene = new Scene(pane, 250, 150);
        primaryStage.setTitle("Display 4 Cards");
        primaryStage.setScene(scene);
        primaryStage.show();
        
    }

    private void shuffle() {
        Collections.shuffle(cards);
        
    }

    public static void main(String[] args) {
        launch(args);
    }

    

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-12-17 15:30:35

您可以为数组实现Fisher-Yates洗牌。

代码语言:javascript
复制
private void shuffle(){
    for(int i = cards.length - 1; i > 0; i--){
        int j = java.util.concurrent.ThreadLocalRandom.current().nextInt(i + 1);
        boolean temp = cards[i];
        cards[i] = cards[j];
        cards[j] = temp;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70395308

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档