Monday, 6 June 2016

Chapter 3 Exercise 14, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

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.

import java.util.Scanner;
 
public class ProgrammingEx3_14 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
 
  System.out.print("Please guess, 0 for head, and 1 for tail:");
  int i = input.nextInt();
  int j = (int) (Math.random() * 2);
 
  if (i == j) {
   System.out.print("You won!!");
  } else {
   System.out.print("You lose!!");
  }
 
 }
 
}

1 comment :

  1. by using int for random there is a lossy conversion this does not work

    ReplyDelete