目录
成员介绍
小组成员 | 负责内容 |
陈泽锴 | 小游戏主体、GUI设计、博客撰写 |
参考博客
1.计算用时 https://blog.csdn.net/weixin_43891901/article/details/103112378
2.文件输入输出 https://blog.csdn.net/web15085181368/article/details/124812429
https://blog.csdn.net/weixin_48029654/article/details/107576595
3.java打包为.exe https://blog.csdn.net/m0_58177653/article/details/126021333
前期调查
通过别人的猜数字游戏的初步设计确认猜数游戏的主体如何设计,之后只需要将主体与设计的GUI适配并引入文件记录用时即可。
https://blog.csdn.net/weixin_64308540/article/details/125916908?spm=1001.2014.3001.5502
项目功能架构图
主要功能流程图
关键代码
1.生成随机数
使用Random生成范围为1到100的随机数。
代码:
Random random = new Random();
number = random.nextInt(100);
2.猜数字游戏主体
使用if-else语句判断所输入的数值,并通过Label显示判断结果。
代码:
String s = InputTextField.getText();
int x = Integer.parseInt(s);
if (x < number) {
ShowLabel.setText("太小了!");
} else if (x > number) {
ShowLabel.setText("太大了!");
} else {
flag1 = 0;
flag2 = 0;
end = System.currentTimeMillis();
totalTime = (int) (end - start) / 1000;
ShowLabel.setText("猜对了!用时为" + totalTime + "s");
3.记录用时
使用System.currentTimeMillis()记录从开始至猜对的用时,并写入记录用时的times.txt文件
代码:
sum = 0;
int i;
start = System.currentTimeMillis();
for (i = 0; i < time; i++) {
sum += i * i;
}
end = System.currentTimeMillis();
totalTime = (int) (end - start) / 1000;
try {
File file = new File("times.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file, true)));
out.write(totalTime + "");
out.write("\n");
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
4.显示排名
使用File将txt内的用时写入数组后排名并展示前五名
代码:
try {
File file = new File("times.txt");
if (!file.exists()) {
file.createNewFile();
}
FileReader reader = new FileReader("times.txt");
BufferedReader readerBuf = new BufferedReader(reader);
List<String> strList = new ArrayList<>();
String lineStr;
while ((lineStr = readerBuf.readLine()) != null) {
strList.add(lineStr);
}
int[] array;
array = new int[strList.size()];
for(int i=0;i<strList.size();i++)
{
array[i] = Integer.valueOf(strList.get(i));
}
Arrays.sort(array);
jLabel1.setText("当前排名(仅显示前5名)");
ShowLabel.setText("第一名 用时"+array[0]+"s");
jLabel2.setText("第二名 用时"+array[1]+"s");
jLabel3.setText("第三名 用时"+array[2]+"s");
jLabel4.setText("第四名 用时"+array[3]+"s");
jLabel5.setText("第五名 用时"+array[4]+"s");
} catch (IOException e) {
e.printStackTrace();
}
运行结果
1.界面
2.点击开始
3.输入数值
4.猜测正确
5.显示排名
项目总结
在本次课程设计中我先是由于不太了解NetBeans设计GUI的方法,因此看了不少教学视频并查了一些博客才有了初步认识,随后在完成课程设计的过程中不断通过实践有了更进一步的认识。除了GUI的设计,将用时保存到文件及从文件中输出用时则是另一个主要困难,我通过查找了许多的博客才找到目前的方法。
在本次课程设计中的显示排名的部分仍有不足,只能采用多个输出框分别输出的方式进行排名展示。之后会尽量改良显示排名的方式。