Given these 9 words, display on the page the word corresponding to their chosen number
1.mercury
2.venus
3.earth
4.mars
5.jupiter
6.saturn
7.uranus
8.neptune
9.pluto
Im not sure what I'm missing here Ive done a lot of trial an error and nothing seems to work.
I've tried using numEntry as my comparison for all the if statements and it hasn't worked. When I made var numEntry = true; only Mercury would display. When I made var numEntry = 1,2,3,4,5,6,7,8,9 only pluto would show. I then tried to create a variable for each number and use each once in a comparison like below but every planet shows up instead of the corresponding number to planet.
var numberOfPlanet = prompt("Please enter a number between 1 and 9");
function thePlanets(){
var numOne = 1;
var numTwo = 2;
var numThree = 3;
var numFour = 4;
var numFive = 5;
var numSix = 6;
var numSeven = 7;
var numEight = 8;
var numNine = 9;
//do I need to define numberEntry if I use it in my comparisons below? what do I define it as after the = //// I tried defining as true but only mercury will appear, i tried inserting numbers 1 through 9 but only pluto worked//
if(numOne = 1 ){
document.write("mercury");
}
if(numTwo = 2 ){
document.write("venus");
}
if(numThree = 3 ){
document.write("earth");
}
if(numFour = 4 ){
document.write("mars");
}
if(numFive = 5 ){
document.write("jupiter");
}
if(numSix = 6 ){
document.write("saturn");
}
if(numSeven = 7 ){
document.write("uranus");
}
if(numEight = 8 ){
document.write("neptune");
}
if(numNine = 9 ){
document.write("pluto");
}
}
thePlanets();
I just need a number to correspond with the right planet when the user enters that number eg. ( user enters 1 and it displays mercury)
Some notes:
Use numberOfPlanet as the function argument to compare with (it becomes num inside the function).
Convert numberOfPlanet to Number as prompt() returns string.
Use === (strong comparison) instead of = (assignment).
Use else if instead of next if if you need only one variant from some so that the comparing stops when the right result is found.
var numberOfPlanet = Number(prompt("Please enter a number between 1 and 9"));
function thePlanets(num){
if(num === 1){
document.write("mercury");
}
else if(num === 2){
document.write("venus");
}
else if(num === 3){
document.write("earth");
}
else if(num === 4){
document.write("mars");
}
else if(num === 5){
document.write("jupiter");
}
else if(num === 6){
document.write("saturn");
}
else if(num === 7){
document.write("uranus");
}
else if(num === 8){
document.write("neptune");
}
else if(num === 9){
document.write("pluto");
}
}
thePlanets(numberOfPlanet);
Related
I am making a game of 21 (also known as blackjacks), and I am not sure why my program is ignoring this conditional statement, where if the user gets their card value above 21, the loop ends, can someone tell me what the problem here would be? Thank you. (This code isn't finished, so excuse the messiness.) (also see comment that says "problem below")
let cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random()*cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random()*cardRange.length)];
var cardTotal = cardOne + cardTwo;
var comScore = 18;
var i;
var extracard;
alert(`Your card numbers are ${cardOne} and ${cardTwo}!`);
//user gets to draw 5 cards in total
for(i = 0; i<3;){
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null){
i+=3;
window.location.replace("http://stackoverflow.com");
}
else if (input === "1"){
i++;
extraCard = cardRange[Math.floor(Math.random()*cardRange.length)];
alert(`This card's number is ${extraCard}!`);
cardTotal = extraCard + cardTotal;
}
else if (input === "0"){
i+=3;
}
//problem below
else if (cardTotal >=22){
i+=3;
}
//not working, loop will not end.
else{
alert("Lmao wrong input you rart");
}
}
function pontoonOutput(){
if (cardTotal > comScore && cardTotal < 22){
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You win!`);
}
else if (cardTotal === comScore){
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... It is a tie!`);
}
//this outputs if the user gets above 22
else if (cardTotal >= 22){
alert("BUST!");
document.write(`Your card number is ${cardTotal}, which is above 21. Which means.... You lose!`);
}
//what should happen if line 29 is picked up. ^
else{
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You lose!`);
}
}
pontoonOutput();
The problem is it is part of an else, so as long as they input 1 or 0 or null, it won't ever hit. Your probably just want to move it into it's own condition at the end:
let cardRange = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var cardOne = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTwo = cardRange[Math.floor(Math.random() * cardRange.length)];
var cardTotal = cardOne + cardTwo;
var comScore = 18;
var i;
var extracard;
alert(`Your card numbers are ${cardOne} and ${cardTwo}!`);
//user gets to draw 5 cards in total
for (i = 0; i < 3;) {
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null) {
i += 3;
window.location.replace("http://stackoverflow.com");
} else if (input === "1") {
i++;
extraCard = cardRange[Math.floor(Math.random() * cardRange.length)];
alert(`This card's number is ${extraCard}!`);
cardTotal = extraCard + cardTotal;
} else if (input === "0") {
i += 3;
} else {
alert("Lmao wrong input you rart");
}
//problem below
if (cardTotal >= 22) {
i += 3;
}
//not working, loop will not end.
}
function pontoonOutput() {
if (cardTotal > comScore && cardTotal < 22) {
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You win!`);
} else if (cardTotal === comScore) {
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... It is a tie!`);
}
//this outputs if the user gets above 22
else if (cardTotal >= 22) {
alert("BUST!");
document.write(`Your card number is ${cardTotal}, which is above 21. Which means.... You lose!`);
}
//what should happen if line 29 is picked up. ^
else {
document.write(`You got ${cardTotal}, and the AI player got ${comScore}. Which means.... You lose!`);
}
}
pontoonOutput();
The problem is that you are checking the card total in the same if...else statement, but AFTER checking for the "0" or "1" input. So if the user enters "0" or "1", your code will process those conditions, and it will never get to the card total check.
There are many ways to fix this problem. One solution is to move the card total check into a separate if condition, after the main if...else logic. Something like this:
for(i = 0; i<3;){
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null){
// ...
}
else if (input === "1"){
// ...
}
else if (input === "0"){
// ...
}
// Keep separate from the main if...else logic to ensure it always gets run.
if (cardTotal >=22){
i+=3;
}
}
Try using the break statement.
Try this instead:
for(i = 0; i<3;){
var input = prompt(`Which makes your card total ${cardTotal}. Would you like to draw another card? (Type in 1 for yes, 0 for no, or select cancel to return to home.)`);
if (input === null){
// ...
}
else if (input === "1"){
// ...
}
else if (input === "0"){
// ...
}
if (cardTotal >=22){
//i += 3;
break;
}
}
now i see, it needed to be splited
I am trying to write a program that prints the numbers from 100 to 200, with three exceptions:
If the number is a multiple of 3, the string "yes" should be returned instead of the number.
If the number is a multiple of 4, the string "yes and yes" instead of the number should be returned.
If the number is a multiple of both 3 and 4, the string "yes, yes and yes" instead of the number.
I am new to JavaScript so I try to do this step by step.
I wrote this code to print the numbers from 100 to 200:
function hundredTwoHundred() {
result = [];
for (let i = 100; i <= 200; i++) {
result.push(i);
}
return result;
}
console.log(hundredTwoHundred());
Then I tried to use else/if for the exceptions:
function hundredTwoHundred() {
result = [];
for (let i = 100; i <= 200; i++) {
if (i % 3 == 0) {
console.log("yes");
} else if (i % 4 == 0) {
console.log("yes and yes")
} else if (i % 3 == 0 && i % 4 == 0) {
console.log("yes, yes and yes");
} else {
result.push(i)
}
}
return result;
}
console.log(hundredTwoHundred());
The code of course, does not work. I have tried moving result.push(i) around, but I don't want to just mindlessly move things around, without knowing the reasoning behind it.
How do I use conditional operators to find these exceptions? What am I doing wrong?
Thank you.
You need to test if the number is (divisible by 3 and divisible by 4) before checking whether it's (individually) divisible by 3 or 4, otherwise the first condition if (i % 3 == 0) will evaluate to true and you'll get yes rather than yes, yes and yes. You should also push to the result in the conditionals rather than console.logging in the conditionals, since you want to create an array of numbers and yeses and then console.log the whole constructed array afterwards.
Also make sure to declare the result with const (or var, for ES5) - it's not good to implicitly create global variables.
Also, although it doesn't matter in this case, when comparing, it's good to rely on === by default rather than == - best to only use == when you deliberately want to rely on implicit type coercion, which can result in confusing behavior.
function hundredTwoHundred() {
const result = [];
for (let i = 100; i <= 200; i++) {
if (i % 3 === 0 && i % 4 === 0) {
result.push("yes, yes and yes");
} else if (i % 3 === 0) {
result.push("yes");
} else if (i % 4 === 0) {
result.push("yes and yes")
} else {
result.push(i)
}
}
return result;
}
console.log(hundredTwoHundred());
If a number is a multiple of 3 and 4, then it is a multiple of 12. I’d also use a switch statement, so you can rewrite as follow:
for (let i = 100; i <= 200; i = i + 1) {
switch (0) {
case i % 12: console.log('yes, yes and yes'); break;
case i % 4: console.log('yes and yes'); break;
case i % 3: console.log('yes'); break;
default: console.log(i);
}
}
If you want it as an array:
// Fill an array with numbers from 100 to 200
const arr = Array(101).fill().map((_, i) => i + 100);
// Map it to numbers and strings
const hundredTwoHundred = arr.map(i => {
switch (0) {
case i % 12: return 'yes, yes and yes';
case i % 4: return 'yes and yes';
case i % 3: return 'yes';
default: return i
}
});
// Print it:
console.log(hundredTwoHundred);
When you have a complex set of conditions you need to be careful with the order in which you evaluate them.
function logExceptions(start, end) {
var divisibleByThree, divisibleByFour;
for (var i = start; i <= end; ++i) {
divisibleByThree = i % 3 == 0;
divisibleByFour = i % 4 == 0;
if (divisibleByThree && divisibleByFour) {
console.log("yes, yes and yes");
}
else if (divisibleByThree) {
console.log("yes");
}
else if (divisibleByFour) {
console.log("yes and yes");
}
else {
console.log(i);
}
}
}
logExceptions(100, 200);
If you want to save the result in an array and only later print it:
function logExceptions(start, end) {
var result = [];
var divisibleByThree, divisibleByFour;
for (var i = start; i <= end; ++i) {
divisibleByThree = i % 3 == 0;
divisibleByFour = i % 4 == 0;
if (divisibleByThree && divisibleByFour) {
result.push("yes, yes and yes");
}
else if (divisibleByThree) {
result.push("yes");
}
else if (divisibleByFour) {
result.push("yes and yes");
}
else {
result.push(i);
}
}
return result;
}
console.log(logExceptions(100, 200).toString());
I have been making a custom function for converting hex to decimal from my scratch project:
function Hex2Decimal(hex){
var deci = 0;
var num = 1;
var hexstr = String(hex);
hexstr = hexstr.toLowerCase();
var expon = 0;
for(var i = 0; i < hex.length; i++){
expon = Math.pow(16,hexstr.length - (num+1));
if(hexstr[num+1] === "a"){
deci = (10*expon)+deci;
}else if(hexstr[num-1] === "b"){
deci = (11*expon)+deci;
}else if(hexstr[num-1] === "c"){
deci = (12*expon)+deci;
}else if(hexstr[num-1] === "d"){
deci = (13*expon)+deci;
}else if(hexstr[num-1] === "e"){
deci = (14*expon)+deci;
}else if(hexstr[num-1] === "f"){
deci = (15*expon)+deci;
}else if(hexstr[num-1] != "undefined"){
deci = (Number(hexstr[num-1])*expon)+deci;
}
num = num + 1;
}
return deci;
}
but when I put "BC324240" into it, it returns the value '197338148' instead of '3157410368.'
When converting the value back to hex, I get 'BC32424.' For some reason, that I need help finding, the '0' in it is completely 'ignored.'
Also noticed that using '10' returns 1...
The following built-in function will do the conversion for you:
dec = parseInt('0x' + hexstr,16);
Just be sure that the number to convert is less than the maximum safe JavaScript integer:
(2^53 - 1) = 0x1fffffffffffff = 9007199254740991.
If you need to work with larger numbers, look at the code here:
https://codegolf.stackexchange.com/questions/1620/arbitrary-base-conversion
I didn't write it, so don't ask me to explain it
You're missing the last position (the digit you should multiply by 16^0) because your call:
expon = Math.pow(16, hexstr.length - (num+1));
is off by one, should be:
expon = Math.pow(16, hexstr.length - num);
Ok so im talking in some unput from the user, it must be 4 numbers, and the digits must not be the same. so everything is working accept the part where i check the 4 numbers against each other. i put the string into an array and then compare the array, by
checking the first one against the 2nd, 3rd, 4th,
then i check the second one against the 3rd, and 4th
then i check the third number against the 4th
My issue is the if statement will not work no matter what i try it gets bypassed everytime. I add random returns into the code to see where it goes and it always returns 12 no matter what even if the numbers i enter are 1111 it still passes.
Ive spent hours trying different stuff please help me!!
function validate(guess){
var user_guess = guess;
var valid = true;
var counter = 0;
parseFloat(user_guess);
if(user_guess.length == 4){
if((user_guess == null) || (isNaN(user_guess))){
validation_alert();
}else{
var guess_string = toString(user_guess);
var guess_array = guess_string.split('');
var guess_array2 = guess_array;
for(var i = 0; i < 3; i++){
counter = i + 1;
for(c = counter; c < 4; c++){
if(guess_array[i] == guess_array2[c]){
return 11;
valid = false;
validation_alert();
}
}
}
if(valid == true){
return 12;
}else{
return 13;
validation_alert();
}
}//if null
}else{
validation_alert();
}//if 4 end tag
}// function close
Just to prove to you that JavaScript uses function scope and not block scope (if else for ...) which means every var you declare moves automatically to the top of the current function it's running in.
Also note that when you return something you will exit the current function and not execute anything after that.
If you check against length you can be sure it's going to be a number so use === instead which checks against it's type (number, string, bool) as well.
Your 2 first if statements should be reversed I think. In anycase user_guess == null will never validate as the previous if checks on the length === 4.
Normally when you use return every block scope should return something. I haven't edited this but that's expected in strict javascript.
It seems more logical to start with valid=false and you will only set it to true when you are sure it's true. I'll leave that up to you.
function validate(guess){
var user_guess = parseFloat(guess),
guess_string,
guess_array,
guess_array2,
valid = true,
counter = 0,
i = 0,
c;
if (!user_guess || isNaN(user_guess)){
validation_alert();
} else {
if (guess.length === 4){
guess_string = user_guess.toString();
guess_array = guess_string.split('');
guess_array2 = guess_array;
for (i; i < 3; i++){
counter = i + 1;
c = counter;
for (c; c < 4; c++){
if (guess_array[i] == guess_array2[c]){
valid = false;
validation_alert();
return 11;
}
}
}
if (valid){
return 12;
} else {
validation_alert();
return 13;
}
} else {
validation_alert();
}
}
}
If you just need to check if the string has 4 unique number digits its much easier this way:
function isValid(str){
var unique={};
for(var i=0;i<str.length;i++){//for each character in the string
unique[str[i]]=true;//we add the character as a key in unique object(the =true doesnt really matter)
}
var chars=Object.keys(unique);//we get an array with the keys in the object(we get an array with the unique characters)
if(chars.length != 4) return false; //if the unique chracters are different than 4, its not valid so return false
chars.sort();//we order the array in lexicographical order
if(chars[0]>= '0' && chars[0] <='9' && chars[3]>= '0' && chars[3] <='9') return true;//if the first character and the last ones are digits, then the ones in the middle wil be digits as well because of the sort we made. If they are, return true
return false;//if they are not both digits, return false
}
console.log(isValid('1111'))//false
console.log(isValid('9230'))//true
console.log(isValid('1343'))//false
console.log(isValid('a412'))//false
console.log(isValid(''))//false
I'm writing a one-line calculator, that has the basic functions (+ - * /). I have done this before, but now I keep getting wrong answers, and I can't find my mistake. Here is my code:
var seq = document.getElementById('sequence').value;
var allNums = [];
var i = 0, allSigns = [];
var currentNums = "";
for (i = 0; i< seq.length; i++)
{
if (seq[i] != "+" && seq[i] != "-" && seq[i] != "*" && seq[i] != "/")
{
currentNums+=seq[i];
}
else
{
allNums.push(Number(currentNums));
currentNums="";
allSigns.push(seq[i]);
}
}
allNums.push(Number(currentNums));
var result = 0;
for (i = 0; i < allNums.length; i++)
{
if (allSigns[i] == '+')
result+=Number(allNums[i]);
else if (allSigns[i] == "-")
result-=Number(allNums[i]);
else if (allSigns[i] == "*")
result*=Number(allNums[i]);
else if (allSigns[i] == "/")
result/=parseInt(allNums[i]);
else
{
alert("The result is: " + result);
break;
}
}
All of this code is in a function, called calculate. The func is triggered by a button, and the sequence comes from an input.
Though there are numerous shortcomings with this simple calculator that may or may not be a problem (depending on what you want to do with it), one issue is that your allSigns array values aren't being associated with the correct allNums array values.
Take a look at this example. In the console, you can see that the sign associated with the 6 is the plus sign, while the operator associated with 2 is undefined. This isn't what we want, of course. What we want is to add the two to the six.
The fix for this issue would be always adding allNums[0] to the result from the start. This sets up our result to be operated upon by anything following it. In this case, we start off with 6.
Next what we need to do is shift the position of each value of allSigns down by one, lining up the operator with the value after it, and not before it. So, in the example above, we'd have + associated with 2, so it'd add the two to the six.
This JSFiddle shows the fix for this specific case.
http://jsbin.com/obasix/3/edit
There are not as many signs as numbers. So therefore, if there are 2 numbers and 1 sign, it will calculate 5 + and then end.
You should start with the result bring the first number.
And then iterate with the remaining numbers and calculate accordingly.
var seq = "5+4";
var allNums = [];
var i = 0, allSigns = [];
var currentNums = "";
for (i = 0; i< seq.length; i++)
{
if (seq[i] != "+" && seq[i] != "-" && seq[i] != "*" && seq[i] != "/")
{
currentNums+=seq[i];
}
else
{
allNums.push(Number(currentNums));
currentNums="";
allSigns.push(seq[i]);
}
}
allNums.push(Number(currentNums));
var result = allNums[0];
for (i = 1; i <= allNums.length; i++)
{
if (allSigns[i-1] == '+')
result+=Number(allNums[i]);
else if (allSigns[i-1] == "-")
result-=Number(allNums[i]);
else if (allSigns[i-1] == "*")
result*=Number(allNums[i]);
else if (allSigns[i-1] == "/")
result/=parseInt(allNums[i]);
else
{
alert("The result is: " + result);
break;
}
}
Try this library https://github.com/notshekhar/calculate.js
Example
<script src="https://raw.githubusercontent.com/notshekhar/calculate.js/main/calculate.js"></script>
<script>
let add = calculate(1, 1, "+") // add -> 2
let sub = calculate(1, 1, "-") // sub -> 0
let mul = calculate(1, 1, "*") // mul -> 1
let div = calculate(1, 1, "/") // div -> 1
let mod = calculate(1, 1, "%") // mod -> 0
</script>