The All on Your Own Exercise - Dice Roll


#1

Can someone offer me some help with this exercise as I'm really struggling

I'm trying to create a Dice Roll on the While Loops in PHP. I have created the following code but haven't really got a clue what it wrong

I get the error

Parse error: syntax error, unexpected T_ELSE on line 20

Yet it tells me I've competed the exercise even though the code is clearly incorrect

<!DOCTYPE html>
<html>
    <head>
    	<link type='text/css' rel='stylesheet' href='style.css'/>
		<title>More Coin Flips</title>
	</head>
	<body>
	<p>We will keep flipping a coin as long as the result is heads!</p>
	<?php
	$DiceRoll = 0;
	do {
		$Dice = rand(0,5);
		$DiceRoll ++;
		if ($Dice){
			echo "<div class=\"dice\">1</div>";
		}
		else {
			echo "<div class=\"dice\">2</div>";
		}
		else. {
			echo "<div class=\"dice\">3</div>";
		}
		else {
			echo "<div class=\"dice\">4</div>";
		}
		else {
			echo "<div class=\"dice\">5</div>";
		}
		else {
			echo "<div class=\"dice\">6</div>";
		}



	} while ($Dice);
	$verb = "Dice";
	$last = "flips";
	if ($DiceRoll == 6) {
		$verb = "was";
		$last = "flip";
	}
	echo "<p>There {$verb} rolled {$last}!</p>";
	?>
    </body>
</html>

#2

It's important to remember that an if statement can have only one else along the main branch.

if () {}

elseif () {}

elseif () {}

elseif () {}

elseif () {}

else {}

Aside:

Variable names should not begin with capitals unless they reference a Class. Use lowercase for first letter (camelCase is okay).

Eg.

$diceRoll = 0;

    $dice = rand(1,6);

Comparison in the if statement...

if ($dice == 1) {}

There is a better tool for this scenario... A switch statement:

https://www.codecademy.com/en/courses/web-beginner-en-jZv2E/0/2

    switch ($dice):
        case 1:
            echo "<div class=\"dice\">1</div>";
            break;

    endswitch;

With a little revision we can save a lot of typing and repetition:

$diceRoll = 0;
do {
    $dice = rand(1,6);
    echo '<div class="dice">';
    switch ($dice) {
        case 1:
            echo "1";
            break;
        case 2:
            echo "2";
            break;
        case 3:
            echo "3";
            break;
        case 4:
            echo "4";
            break;
        case 5:
            echo "5";
            break;
        case 6:
            echo "6";
    }
    echo '</div>';
    $diceRoll++;
} while ($diceRoll < 5);

But this is misleading.There is no real need for any kind of control flow logic. We can write one line per iteration and use string interpolation in the string.

<?php
  // Yahtzee player turn
  $diceRoll = 0;
  do {
    $dice = rand(1,6);
    echo "<div class=\"dice\">$dice</div>";
    $diceRoll++;
  } while ($diceRoll < 5);
?>

The outer quotes must be doublequote for this to parse correctly.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.