-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCoinFlipGrid.java
More file actions
70 lines (61 loc) · 2.32 KB
/
CoinFlipGrid.java
File metadata and controls
70 lines (61 loc) · 2.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
Rahim Siddiq
Apr 28 2023
Game: Nine heads and tails
*/
import java.util.Scanner;
public class CoinFlipGrid
{
public static void main(String[] args)
{
// Program variables - Create a variable to store user input and a 3x3 integer matrix
int numChoice = 0;
int [][] matrixHT = new int[3][3];
// Title of program and description of program function to user
System.out.println(" ====================================================================");
System.out.println(" ============== Heads or Tails: 3x3 Matrix Outcomes ================");
System.out.println(" ====================================================================");
System.out.println(" This program creates a grid for the 512 possible conbinations ");
System.out.println(" of flipping 9 coins and displays them in a 3x3 matrix ");
System.out.println(" --------------------------------------------------------------------");
System.out.println();
// Scanner object for input
Scanner input = new Scanner(System.in);
// User input
System.out.print(" Enter a number between 0 and 511: ");
numChoice = input.nextInt();
// Keep input in range
while(numChoice < 0 || numChoice > 511)
{
System.out.print(" Please make sure the number is between 0 and 511. Please re-enter: ");
numChoice = input.nextInt();
}
// For loop takes the user input and uses the % operator to populate the arrays with 0 or 1
for (int i = 2; i >= 0; i--)
{
for (int j = 2; j >= 0; j--)
{
matrixHT[i][j] = ((numChoice % 2) == 0 ? 0 : 1);
numChoice = numChoice / 2;
}
}
// Print the matrix for 0 in % division print H, for 1 print T
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (matrixHT[i][j] == 0)
{
System.out.print(" H ");
}
else
{
System.out.print(" T ");
}
}
System.out.println();
}
// Close the Scanner to prevent resource leak
input.close();
}
}