|
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
Do you have a Java Problem?
Java Books
Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|