[Solved] Vending Machine - PHP Task

  

3
Topic starter

Your task is to calculate the total price of a purchase from a vending machine. Until you receive "Start" you will be given different coins that are being inserted in the machine. You have to sum them in order to have the total money inserted. There is a problem though. Your vending machine only works with 0.1, 0.2, 0.5, 1, and 2 coins. If someone tries to insert some other coins you have to display "Cannot accept {money}" and not add it to the total money. On the next few lines until you receive "End" you will be given products to purchase. Your machine has however only "Nuts", "Water", "Crisps", "Soda", "Coke". The prices are: 2.0, 0.7, 1.5, 0.8, 1.0 respectively. If the person tries to purchase a not existing product print “Invalid product”. Be careful that the person may try to purchase a product they don’t have the money for. In that case print "Sorry, not enough money". If the person purchases a product successfully print "Purchased {product name}". After the "End" command print the money that are left formatted to the second decimal point in the format "Change: {money left}".

Hint: You can use round() method with precision.

Examples:

vending machine php task

1 Answer
2

Here is my solution:

<?php
 
$sum = 0;
$price = 0;
$input = readline();
 
while ($input !== 'Start') {
 
    if ($input == '0.1' || $input == '0.2' || $input == '0.5' || $input == '1' || $input == '2') {
        $sum += round($input, 2);
    } else {
        echo 'Cannot accept ' . $input . PHP_EOL;
    }
    $input = readline();
}
$input = readline();
 
while ($input !== 'End') {
 
    switch ($input) {
        case 'Nuts':
            $price = 2.00;
            break;
        case 'Water':
            $price = 0.70;
            break;
        case 'Crisps':
            $price = 1.5;
            break;
        case 'Soda':
            $price = 0.80;
            break;
        case 'Coke':
            $price = 1.00;
            break;
        default:
            echo 'Invalid product' . PHP_EOL;
            $price = 0;
    }
 
    if ($sum < $price) {
        echo 'Sorry, not enough money' . PHP_EOL;
    } else if ($price !== 0) {
        $sum -= $price;
        echo 'Purchased ' . strtolower($input) . PHP_EOL;
    }
 
    $input = readline();
}
 
printf("Change: %.2f", $sum);
Share: