键盘录入数据,使用Math类的random方法来实现猜数字游戏
程序员文章站
2024-03-22 16:44:23
...
import java.util.Scanner;
import java.text.DecimalFormat;
class Caishuziyouxi
{
public static void main(String[] args)
{
int a = (int)(Math.random()*100+1);
Scanner sc = new Scanner(System.in);
DecimalFormat df = new DecimalFormat("######0.000000000");
int i= 0;
int j= 0;
int k= 0;
while (true)
{
System.out.println("请输入你要猜的数字");
int guess = sc.nextInt();
if ( guess > a)
{
System.out.println("你输入的数字大了");
j++;
}else if (guess < a)
{
System.out.println("你输入的数字小了");
k++;
}else{
System.out.println("恭喜你,猜中了");
i++;
System.out.println("你输入大了"+j+"次");
System.out.println("你输入小了"+k+"次");
System.out.println("你一共输入了"+(k+j+1)+"次");
System.out.println("你一共赢了"+i+"把");
System.out.println("你还想玩吗,输入是继续玩,输入否不玩");
String str = sc.next();
char shi = str.charAt(0);
if (shi=='是')
{
a = (int)(Math.random()*100+1);
continue;
}else if (shi=='否')
{
break;
}{
break;
}
}
double q = 1/(k+j+1);
System.out.println("你的正确率是"+df.format(q));
}
}
}
下一篇: 散列表(Hash table)