2016-04-24 26 views
0

我的任務是要我們用圖像問一個問題(使用我在java項目中導入的圖像文件)。我如何從我的方法中選擇一個隨機圖像文件?例如,在我的第二行代碼中,我有一個顯示圖片的圖像文件,該文件來自下面的「states_capitals」方法。我該如何改變它,只顯示我列出的隨機文件圖像?如何從方法中選取隨機圖像來顯示?

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);  
}  

回答

1

在概念上,你會簡單地創建一個Random對象,然後使用nextInt(int n)方法中,創建0之間以及陣列的長度的隨機數,並引用信息通過所創建的數字,陣列英寸如果您需要幫助,請參閱java API瞭解Random類。

您可能還想考慮將問題的所有信息分組到一個問題類中,以便於操作,讀取和訪問。