java 猜数字游戏

来源:互联网 发布:西门子plc数据用于联网 编辑:程序博客网 时间:2024/05/17 05:05
import java.util.Scanner;
import java.util.Random;


public class Guest{
public static void main(String[] args){

Random rand = new Random();

Scanner input = new Scanner(System.in);

int index = 0;                //猜的轮数
int[] counts = new int[2];
String answer = "y";
do{
int count = 1;
int randNum = rand.nextInt(101);         //生成100以内一个随机数
System.out.print("请输入你猜的数:");
int guestNum = input.nextInt();//猜一个100以内的数

//判断猜对了 、猜大了、猜小了
while(true){
if(guestNum>randNum){
System.out.print("\n很抱歉,你猜错了,猜的偏大。\n请重新猜一次:");
guestNum = input.nextInt();
count++;
}else if(guestNum<randNum){
System.out.print("\n很抱歉,你猜错了,猜的偏小。\n请重新猜一次:");
guestNum = input.nextInt();
count++;
}else{
System.out.println("\n恭喜你猜对了,共用了"+count+"次");
break;
}


}
//超过数组长度
if(index==counts.length){
int[] tempCounts = new int[counts.length+10];
for(int i = 0;i<counts.length;i++){
tempCounts[i] = counts[i];
}
counts = tempCounts;
tempCounts = null;
}
counts[index++]= count;
System.out.print("\n是否继续游戏(除了n之外都是继续):");
answer = input.next();
}while(!"n".equals(answer));


//每一次的成绩
for(int i = 0;i<index;i++){
System.out.print("\n\t第"+(i+1)+"次成绩是:"+counts[i]);
}

//显示最好成绩
int bestRecord = 100;
for(int i = 0;i<index;i++){
if(counts[i]<bestRecord){
bestRecord = counts[i];
}
}
//最好次数对应的轮数
System.out.print("\n\t最好成绩是第");
for(int i = 0;i<index;i++){
if(counts[i]==bestRecord){
System.out.print(i+1+"次");
}
}
System.out.print(",成绩是:"+bestRecord);
}
}
0 0