第三章第十四题(游戏:猜硬币的正反面)(Game: heads or tails)
3.14(游戏:猜硬币的正反面)编写程序,让用户猜一猜是硬币的正面还是反面。这个程序随机产生一个整数 0 或者 1,它们分别表示硬币的正面和反面。程序提示用户输入一个猜测值,然后报告这个猜测值是正确的还是错误的。 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.参考代码:
package chapter03;
import java.util.Scanner;
public class Code_14 {
public static void main(String[] args) {
final int coin = (int)(Math.random() * 2);
int userGuess;
System.out.print("Enter a guess,0 for head,1 for tail:");
Scanner input = new Scanner(System.in);
userGuess = input.nextInt();
if(userGuess != 0 && userGuess != 1)
{
System.out.println("Error: invalid status");
System.exit(1);
}
else if(coin == userGuess)
System.out.println("You are correct!");
else if(coin != userGuess)
System.out.println("Your are wrong!");
input.close();
}
}
结果显示:
Enter a guess,0 for head,1 for tail:1
Your are wrong!
Process finished with exit code 0
转载请注明原文地址:https://blackberry.8miu.com/read-5155.html