代码如下:
import java.util.Scanner; public class GuessCoin {
/* (1)抛硬币游戏:
用0,1代表“正面”,“反面”
在后台抛出一枚硬币,在前台读入用户猜的结果,结果正确在控制台打印
(或者弹窗)输出“猜对了!”,否则输出“猜错了!”。*/
public static void main (String[] args) {
final long COIN_HEAD = 0;
final long COIN_TAIL = 1;
Scanner sc = new Scanner(System.in);
System.out.println("猜硬币:0=硬币正面和1=硬币反面,请输入:");
while (sc.hasNextInt()) {
int guess = sc.nextInt();
if (guess != COIN_TAIL && guess != COIN_HEAD) {
System.out.println("输入有误!");
continue;
}
int coin = (int) Math.round(Math.random());
System.out.println(guess == coin ? "猜对了!" : "猜错了!");
System.out.println("猜硬币:0=硬币正面和1=硬币反面,请输入:");
}
System.out.println("退出!");
}
}