Comencé mi ruta de aprendizaje de codificación y me encontré con un contratiempo. Estoy tratando de escribir un programa que represente lo siguiente;
// Write a program that prints a message to the screen based on a users age and country. // Feel free to change these variables or create new ones so you can test all cases. const age = 20 const country = 'USA' // if the user is younger than 16 print "You're not old enough to do anything yet." // if the user is at least 16 but not yet 18 print "Be careful driving." // if the user is 18 but not yet 21 and the user lives in the USA pring "Go Vote!" // if the user is at least 18 but younger than 21 and lives outside of the US print "You can probably have some wine." // In all other cases print "You're old enough to figure it out for yourself."Hasta ahora tengo esto:
const age = 20 const country = "USA" const otherCountry = "Other country" console.log(age) console.log(otherCountry) if (age < 16 ) { console.log("You're not old enough to do anything.") } else if (age >=16 && age <=18) { console.log ("Be careful driving") } else if (age >=18 && age <=21 && country) { console.log("Go Vote!") } else if (age >=18 && age <=21 && otherCountry){ console.log ("You can prbably have some wine") } else {console.log ("You're old enough to figure it out") }Parece que no puedo entender cómo hacer que el país se exprese en la declaración "si no". Los novatos tienen que empezar en alguna parte. Gracias por adelantado
Tienes un problema con tu lógica.
En primer lugar , aún no 18 probablemente significa < 18 y no <= 18 . (lo mismo para 21)
En segundo lugar, una vez que esté en su rama "Go vote" , nunca más podrá ingresar a la rama "Wine" , porque una vez, se cumple una condición en un if .. else if .. else ya no se evaluarán otras condiciones.
Entonces, si tiene una persona entre 18 y 21 años, debe verificar la condición adicional (es decir, vive en EE. UU. O cualquier otro país) en esa sucursal.
let age = 19; let livesin = "USA"; if (age < 16 ) { console.log("You're not old enough to do anything.") } //you don't need >=16 here, because as the first condition failed //we alread know that age >= 16 else if (age < 18) { console.log ("Be careful driving") } //you don't need >=18 here, because as the first and second condition failed //we already know that age >= 18 else if (age <21) { //for people between 18 and 21, check if they live in the USA or not if (livesin === "USA") console.log("go vote"); else console.log("You can prbably have some wine") } else { console.log ("You're old enough to figure it out") }