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.
Solution:
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int randomNumber, guess;
System.out.print("Enter a guess(0 or 1):");
guess = s.nextInt();
if(guess == 0 || guess == 1) {
randomNumber = (int)(Math.random() * 2);
if(guess == randomNumber) {
System.out.print("You won.");
} else {
System.out.print("You lose.");
}
} else {
System.out.print("The number you entered is not valid.");
}
}
package coins;
ReplyDeleteimport java.util.*;
/**
*
* @author Student
*/
public class Coins {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner console = new Scanner(System.in);
int number = (int)Math.random()*2;
int guess;
System.out.print("Enter a guess(0 or 1):");
guess = console.nextInt();
if(guess ==number)
System.out.println("correct");
else if(number ==0)
System.out.println("sorry it was tail");
else
System.out.println("The number you entered is not valid.");
}
}
This one worked for me
package chapter3.Exercises;
ReplyDeleteimport java.util.Scanner;
public class Exercise_3_14 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number = (int) (Math.random() * 2);
System.out.println("heads or tails? ");
String guess = input.nextLine();
if(guess.equals("heads") || guess.equals("tails")){
if(guess.equals("heads") && number == 0 ) {
System.out.println("Congratulations! Your guess is correct ");
}else if (guess.equals("tails") && number == 1 ){
System.out.println("Congratulations! Your guess is correct ");
}else {
System.out.println("Sorry:( Your guess is incorrect ");
}
}else {
System.out.println("Invalid Entry");
}
}
}