- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Java Program to Toss a Coin
Let’s say we have a coin and 10 chances. Here, we will first initialize the values for head, tail and chances −
int heads = 0; int tails = 0; int chances = 10;
Now, we will get the head and tail values using the Random object −
for (int i = 1; i<= chances; i++) { if (t.chanceFunc().equals("tails")) { tails++; } else { heads++; } }
Above, the function chanceFunc() is having Random class with the nextInt() method to get the next random value. The condition is checked and the heads and tails values are returned −
public String chanceFunc() { Random r = new Random(); int chance = r.nextInt(2); if (chance == 1) { return"tails"; } else { return"heads"; } }
Example
import java.util.Random; class Toss { public String chanceFunc() { Random r = new Random(); int chance = r.nextInt(2); if (chance == 1) { return"tails"; } else { return"heads"; } } } public class Demo { public static void main(String[] args) { Toss t = new Toss(); int heads = 0; int tails = 0; int chances = 10; for (int i = 1; i<= chances; i++) { if (t.chanceFunc().equals("tails")) { tails++; } else { heads++; } } System.out.println("Chances = " + chances); System.out.println("Heads: " + heads); System.out.println("Tails: " + tails); } }
Output
Chances = 10 Heads: 3 Tails: 7
Let us run the program again −
Chances = 10 Heads: 4 Tails: 6
Advertisements