package dsasda;
import java.io.*;
import java.util. *;
public class GuessNumber {
public static void main(String[] args)throws IOException{
//创建键盘录人对象
Scanner input=new Scanner(System.in);
//创建字符流对象
Writer fw=null;
//定义参加游戏的用户人数
System.out.print("请输入参与游戏的用户人数:");
int user=input.nextInt();
//定义猜测的次数
int count;
//用数组来存放猜测次数
int[]counts=new int[user];
//定义成绩
int score=0;
//捕获可能出现的异常,例如:输入所猜数不是数字,是A
try{
//循环控制人数
for(int i=0;i<user;i++){
//初始化
count=0;
System.out. println("*****您是第"+(i+1)+"位用户*****");
System.out. print("请输入您的姓名:");
String name =input.next();
//生成随机数作为要猜的数
int number =(int)(Math.random()*100+1);
long startTime= System.currentTimeMillis();//获取程序开始时间
System.out.print("请输入您猜的数:");
int guessnum =input.nextInt();
count++;//次数加1
counts[i]+=1;
//通 过while过循环,进行猜数字对错判断
//猜错,继续游戏;猜对,跳出循环,游戏结束
while(guessnum!= number){
//猜错了,根据结果,给出提示,接着猜数,游戏继续
if(guessnum>100||guessnum<0){
System.out. println("输入有误,请重新输入!");
return;
}else if(guessnum>number){
System.out.print("猜大了,请重新猜测:");
guessnum=input.nextInt();
count++;
}else{
System.out.print("猜小了,请重新猜测:");
guessnum=input.nextInt();
count++;
}
}
long endTime= System.currentTimeMillis();//获取结束时间
//由于猜测次数可能相同,所以把猜测次数与时间相加作为分数
score=(int)((endTime-startTime )/1000)+ count;
counts[i] =score;
System.out.println("恭喜您,猜对了!此次游戏的正确答案是:"+number);
System.out. println("您一共猜测了"+count+"次猜数时长为:"+(endTime-startTime)/1000+"s");
//输出给该用户的评语
System.out.print("评语:");
switch(count){
case 1:
System.out.println("您太棒了,一次就猜对了!");
break;
case 2:
case 3:
case 4:
case 5:
System.out.println("不错嘛!这么快就猜对了!");
break;
case 6:
case 7:
System.out. println("有点遗憾,再接再厉哦!");
break;
default:
System.out.println("猜了这么久才猜对,还要多多练习哦!");
break;
}
System.out.println("您的成绩是:"+score+"分");
//写入文件
fw =new FileWriter("D:\\GuessNumberGame\\read.txt",true);
fw.write("用户姓名:");
fw.write(name);
fw.write("/t");
fw.write("所用时间:");
long time=((endTime-startTime)/1000);
String timel=Long.toString(time);
fw.write(timel);
fw.write("");
fw.write("用户成绩:");
String scorel =Integer. toString(score);
fw. write(scorel);
fw.write("分\t");
System.out. println("保存成功!n");
fw.close();
}
}catch(Exception e){
e.printStackTrace();
//排行榜
}
System.out.println("********排行榜*********");
//根据用户所得分数来进行排序,分数较少位于排行榜前方
Arrays.sort(counts);
for(int scores:counts){
System.out.println(scores+"\t");
System.out. println("******************\n");
}
System.out. println("本轮游戏结束,大家可以退出游戏了!\n");
}
}