I am currently working on a simple product machine using node/terminal and i have run into a problem. I have added an array with number ID's relating to the element. And i am using readline to ask what product the user would like.
When entering ID 1 it provides the successful message for a drink. But when entering 2, 3 or 4. Nothing happens?
Can anyone see what i am doing wrong here, i would really appreciate it!
Kind Regards!
var readlineSync = require('readline-sync'),
products = [];
products[1] = "Drink";
products[2] = "Crisps";
products[3] = "Chocolate";
products[4] = "Candy";
var productPurchase = readlineSync.question('Would you like to purchase a product? ');
if (productPurchase == "yes") {
index = readlineSync.keyInSelect(products, 'What product would you like?');
if (index == [1]) {
console.log('Thank you, your Drink' + ' has now been dispensed.');
if (index == [2]) {
console.log('Thank you, your Crisps' + ' has now been dispensed.');
if (index == [3]) {
console.log('Thank you, your Chocolate' + ' has now been dispensed.');
if (index == [4]) {
console.log('Thank you, your Candy' + ' has now been dispensed.');
}}}}}
Your nested if's will never be executed, index cannot both be 1 and 3 at the same time. I would suggest you use a switch instead, it is basically what you are trying to do :
var productPurchase = readlineSync.question('Would you like to purchase a product? ');
if (productPurchase == "yes") {
index = readlineSync.keyInSelect(products, 'What product would you like?');
switch (index) {
case 1 :
console.log('Thank you, your Drink' + ' has now been dispensed.');
break;
case 2 :
console.log('Thank you, your Crisps' + ' has now been dispensed.');
break;
case 3 :
console.log('Thank you, your Chocolate' + ' has now been dispensed.');
break;
case 4 :
console.log('Thank you, your Candy' + ' has now been dispensed.');
break;
default :
console.log('something went wrong');
break;
}
}
NB : Have corrected the wrong usage of index. keyInSelect() returns the index as a number, not as an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With