Coin Toss Programming Simulator

The program currently contains three classes. 

Here is the source code for each:
 
CoinToss.java (Main)
 
public class CoinToss {
 
  public static void main(String[] args) {
 
    System.out.println("Heads or Tails?");
 
    Coin c = new Coin();
 
    c.chance();
 
    CoinTossHelper check = new CoinTossHelper();
 
    String userGuess = check.getUserInput("Type Heads or Tails");
 
    String result = c.checkInput(userGuess);
 
    if(result.equals("Valid")) {
 
      System.out.println(c.getSide() + " You win!");
 
    } else if(result.equals("Invalid")) {
 
      System.out.println(c.getSide() + " You lose.");
 
    } else {
 
      System.out.println("An error has occured.");
 
    }
 
  }
 
}
 
 
Coin.java
 
public class Coin {
 
  private String side;
 
  private String result;
 
  String[] choices = {"1","2"};
 
  int length = choices.length;
 
  public void chance() {
 
    int rand1 = (int) (Math.random()*length);
 
    String num = choices[rand1];
 
    if(num == "1") {
 
      side = "Heads";
 
    }
 
    else if(num == "2") {
 
      side = "Tails";
 
    }
 
  }
 
  public String getSide() {
 
    return side;
 
  }
 
  public String checkInput(String userGuess) {
 
      if(userGuess.equals(side)) {
 
      result = "Valid";
 
    } else {
 
      result = "Invalid";
 
    }
 
    return result;  

  }
 
}
 
 
CoinTossHelper.java
 
import java.io.*;
 
public class CoinTossHelper {
 
  public String getUserInput(String prompt) {
 
    String inputLine = null;
 
    System.out.print(prompt + " ");
 
    try {
 
      BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
 
      inputLine = is.readLine();
 
      if (inputLine.length() == 0) return null;
 
    } catch(IOException e) {
 
      System.out.println("IOException: " + e);
 
    }
 
    return inputLine;
 
  }
 
}

See also
Coding Bubble Sort in Java

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.