3.14
(Game: heads or tails) Write a program that lets the user guess whether the flip of
a coin results in heads or tails. The program randomly generates an integer 0 or 1,
which represents head or tail. The program prompts the user to enter a guess and
reports whether the guess is correct or incorrect.
3.14
(游戏:正面还是反面)编写一个程序,让用户猜测抛硬币的结果是正面还是反面。程序随机生成一个整数0或1,表示头或尾。程序提示用户输入猜测,报告猜测是否正确。
代码如下:
import java.util.Scanner;
public class Unite3Test14
{
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("请输入你的猜测(正面是true 反面是 false)");
boolean idea=input.hasNextBoolean();
int num = (int)(Math.random() );
if(num==0&&idea==true)
{
System.out.println("你猜对了");
}else if (num==0&&idea==false)
{
System.out.println("你猜错了");
}else if (num==1&&idea==false)
{
System.out.println("你猜对了");
}else if (num==1&&idea==true)
{
System.out.println("你猜错了");
}
}
}
结果如下: