helpmeplease
helpmeplease

Reputation: 15

How to pick a random image from a method to display?

My assignment wants us to ask a question with an image (using an image file I imported in my java project). How do I pick a random image file from my method? Example, in my 2nd line of code, I had an image file that displays a picture and that file is from "states_capitals" method below. How do I change it in a way where it would just show a random one of the file images I have listed?

public void start(Stage primaryStage){

    ImageView us = new ImageView(new Image("file:///Users/flag.png"));

    Scene scene = new Scene (pane2, 600, 300);
    primaryStage.setScene(scene);
    primaryStage.show();   

    submit_button.setOnAction(e -> {
        correct_wrong();
    });
}

private void correct_wrong () {
    String index = answer_box.getText();   

    Map<String, String> mapStateCapitals = new HashMap<>(50);
    for (String[] stateCapital : states_capitals) {
        mapStateCapitals.put(stateCapital[0], stateCapital[1]);
    } 

    mapStateCapitals.forEach((state, capital) -> {    
        if (index.equalsIgnoreCase(capital)) {
            answer_result.appendText("Correct!");
        } else {
            answer_result.appendText("WRONG - The correct answer is " + capital);
        }
    });
}

private static String[][] states_capitals = {
        {"file:///Users/flag.png", "Siri"},
        {"file:///Users/flag.png2.png", "Juju"},
        {"file:///Users/flag.png3.png", "Cambodia"},           
};

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

Upvotes: 0

Views: 522

Answers (1)

MercyBeaucou
MercyBeaucou

Reputation: 268

Conceptually, you would simply create a Random object, and then using the nextInt(int n) method, create a random number between 0 and the length of the array, and reference the info in that array through the number you created. If you need help with that, see the java API for the Random class.

You may also want to consider grouping all the info for a question into a question class, to make it easier to manipulate, read, and access.

Upvotes: 1

Related Questions