【发布时间】:2016-01-23 22:54:26
【问题描述】:
我正在尝试使用 JFrame 创建一个记忆匹配游戏。我正在使用一个包含 .png 文件(国家标志)的文件夹,它将使用以下代码填充字符串数组:
public String[] listPngFiles(String filePath) {
File[] fileReader = fileReader(filePath);
String[] files = new String[fileReader.length];
for(int i=0; i<files.length; i++)
files[i] = "" + fileReader[i];
arraySize = files.length;
return files;
}
public File[] fileReader(String filePath) {
File folder = new File(filePath);
return folder.listFiles (new FilenameFilter() {
public boolean accept(File filePath, String filename)
{ return filename.endsWith(".png"); }
});
}
我这样做的原因是因为我想创建一个动态 JButton 数组,该数组以随机顺序保存每个标志,两次。每次执行程序时,标志都必须重新洗牌。
这是我目前正在处理的代码:
int[] flags = new int[arraySize*2];
for (int i=0; i<flags.length; i++){
flags[i] = -1; // -1 represents "no flag"
for (int r=0; r<2; r++)
{
int pos=0;
do
{
pos = randomize();
flags[pos] = i; // put the flag into the card at the available position
}
while (flags[pos] != -1); // if card[pos] is not -1, it already has a flag in it
}
}
非常感谢您对此事的帮助。
【问题讨论】:
-
旁注:不要使用数组,而是使用 ArrayList / List。
-
使用
List,并使用Collections.shuffle。
标签: java arrays eclipse random jframe