這里我的代碼(在 Eclipse 上的 Java 中)顯示了來自 a 檔案的 3 張隨機卡片。我試圖讓一個洗牌按鈕作業并隨機洗牌 3 張新卡。我使用了“Collections.shuffle(cards);” 并將它傳遞給我的布爾陣列,但它說我不能,因為它想要一個 List<> 串列。是否可以讓 shuffle 與我的布林值一起使用,還是我必須使用 List?
這是我的代碼:
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);
}
}
uj5u.com熱心網友回復:
您可以對陣列實施 Fisher–Yates shuffle。
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;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/383714.html
