0

I'm writing a program where it tracks how many flips you want to perform and then it lists the results.

public static void main(String[] args) {
    Scanner scnr = new Scanner(System.in);
    Random rand = new Random();
    int flips;
    int coin;
    int i;
    String result;

    System.out.println("Welcome to the coin flip analyzer.");
    System.out.print("How many flips? ");

    flips = scnr.nextInt();

    for (i = 0; i < flips; ++i) {
        coin = rand.nextInt(2);
        if (coin == 0) {
            result = ("H");
            System.out.print(result);
        }
        else {
            result = ("T");
            System.out.print(result);
        }   
    }
}

For example, for a flips of 10:

Welcome to the coin flip analyzer.

How many flips? 10

HHTHTHHHTT

What I'm trying to change in my code is adding a space when a coin run ends. For example, the above result would look like:

HH T H T HHH TT
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

1

You compare the current value to the previous and emit a space if they are different.

String result = null;

System.out.println("Welcome to the coin flip analyzer.");
System.out.print("How many flips? ");

flips = scnr.nextInt();

for (i = 0; i < flips; ++i) {
    String oldResult = result;
    coin = rand.nextInt(2);
    if (coin == 0) {
        result = "H";
    } else {
        result = "T";
    }   
    System.out.print(result);
    if (oldResult != null && !oldResult.equals(result)) {
        System.out.print(' ');
    }
}
Leo Aso
  • 11,898
  • 3
  • 25
  • 46
0

You can store the previous result, and then compare.

Scanner scnr = new Scanner(System.in);
Random rand = new Random();

System.out.println("Welcome to the coin flip analyzer.");

System.out.print("How many flips? ");
int flips = scnr.nextInt();

String previousResult = null;
String result;
for (int i = 0; i < flips; ++i) {
    result = rand.nextInt(2) == 0 ? "H" : "T";
    System.out.print(!result.equals(previousResult) ? " " + result : result);   
    previousResult = result;
}

For the syntax I used in the loop, you can refer Java - Ternary

Sample

Welcome to the coin flip analyzer.
How many flips?  10
T H T H TT H TTT
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245