I am defining a function that takes three numbers as arguments and returns the largest of them.
Here is my code:
var instructions = alert("Choose a set of numbers to input for the computer to determine which value is the largest");
var inputOne = prompt("Please input your first desired value");
var inputTwo = prompt("Please input your second desired value");
// THIS ARRAY STORES THE VALUES OF inputOne && inputTwo
var maxInput = Math.max([inputOne, inputTwo]);
var inputThree = prompt("Please input your third desired value");
// THIS WILL COMPARE BETWEEN THE inputThree && THE MAX INPUT OF THE USERS FIRST TWO CHOICES
var maxNumber = Math.max(maxInput, inputThree);
//validate if inputs are numbers and not letters
// isNaN()
var compare = function (maxNumber, inputThree) {
if (inputThree === maxNumber) {
return alert("The result is the same!");
} else if (inputThree != maxNumber) {
return alert(maxNumber + " " + "is the larger value!");
}
}
compare(maxNumber, inputThree);
Now I'm getting a result of "NaN is the larger value!" and it's driving me crazy! I tried running console.log to see where I'm getting NaN but that didn't work at all. All that did was log NaN to the console.
I also tried taking the parameters out of Math.max( ) however was just getting:
"-infinity is the larger value!"
Can someone at least give me a hint as to why this is happening? Or explain to me further what is going on.
Math.max([inputOne, inputTwo]) should be Math.max(inputOne, inputTwo)
Why don't you just get the largest of all of them with just
var maxNumber = Math.Max(inputOne, inputTwo, inputThree);
Here:
var inputThree = prompt("Please input your third desired value");
inputThree is a String (i.e. its value has a Type of String), always. And here:
var maxNumber = Math.max(maxInput, inputThree);
maxNumber is a Number, always (because that's what Math.max returns, even though the arguments are Strings). So:
inputThree === maxNumber
is always false, because a Number is never equal to a String (see the Strict Equality Comparison Algorithm). So either convert inputThree to a Number, e.g.
+inputThree === maxNumber
or use ==.
inputThree == maxNumber
Related
choice = input.questionFloat('\t1. Display all members\' information \n\t2. Display member information \n\t3. Add new member \n\t4. Update points earned \n\t5. Statistics\n\t6. Exit \n\t>> ');
if (choice.toString().includes('.')) {
console.log ('Please enter a valid input.');
}
choice contains the input from the user. If choice is a floating number, it will prompt the user that it is a invalid input. If there a better way of doing this instead of using .includes?
You can do that easily with JavaScript.
First take and convert to number and check if it's truthy value (non NaN) and check if it's not integer.
const num = Number('123.3')
if (num && !Number.isInteger(num)){
//float
}
Why not compare it to its value in int?
const intValue = 12
console.log(parseInt(value) !== value) // false => is an int
const floatValue = 12.1
console.log(parseInt(value) !== value) // true => is not an int
I am trying to get user input and then put this into an array, however, if the user puts in an element that is not a number how can I remove this? I can make an error message show up however the element still goes into the array.
var input_array = [];
var number = prompt('Enter a Number');
if (isNaN(number)) {
alert("Please Enter a Number");
}
var array = input_array.push(parseInt(number));
Just place the push inside an else. Also note that push returns the new length of the array - so array will be 1 in your code.
var input_array = [];
var number = prompt('Enter a Number');
if (isNaN(number)) {
alert("Please Enter a Number");
} else {
input_array.push(parseInt(number));
}
console.log(input_array);
This is a neat way of doing it using the ternary operator. Only add the input to array if it is a number.
var input_array = [];
var number = prompt('Enter a Number');
isNaN(number) ? alert('Please Enter a number'): input_array.push(number);
Also prompt returns a string, so if you want your array to contain only numbers. Use parseInt when reading input
var number = parseInt(prompt('Enter a Number'));
Ask user for a number. Determine if the number is even or odd. I have my constants set and using modulo to figure this out. However I am stuck in an infinite loop and can't figure out why. I have my if statement in the loop as well as a break statement to get out, but still in an infinite loop.
HAVE TO USE A WHILE LOOP
// declare constants
const MODULO = 2;
const EVEN = 0;
const ODD = 1;
// declare variables
var enteredNumber;
var result;
// prompt user to enter an even number
enteredNumber = prompt("Enter an even number: ");
// convert user input into a number
enteredNumber = Number(enteredNumber);
// determine result of modulo equation
result = enteredNumber % MODULO;
// while loop to check if enteredNumber is even or odd
while (result === EVEN) {
document.write(enteredNumber + " is an even number <br/>");
enteredNumber = prompt("Enter an even number: ");
enteredNumber = Number(enteredNumber);
result = enteredNumber % MODULO;
if (result === ODD) {
document.write(enteredNumber + " isn't an even number");
break;
}
}
You can essentially one-liner this thing. You're already checking stuff with the while.
document.addEventListener('DOMContentLoaded', () => {
while (!(parseInt(window.prompt('Enter an even number', '2') || '1', 10) % 2)) { };
});
Why this works
Javascript has 'falsy' and 'truthy' values.
window.prompt('Enter an even number', '2')
This code prompts the user for a number. The result is a string (or null, if the user blanks out the prompt).
<a string or null> || '1'
If the user blanked out the prompt, it will return null. In Javascript we can use the or operator to choose between two things. null || '1' reads from left to right. The first thing is falsy so it chooses '1'.
If the user entered a number (like 10), we would get the number they entered as a string.
Then we parse the string to a number with parseInt.
Take that result and use the modulo operator % to divide by the operand and return the remainder. When you divide by 2 the remainder will either be 0 or 1. These are falsy/truthy values.
while(0) evaluates to false and breaks the loop. while(1) evaluates to true and continues the loop.
This question already has answers here:
Why is typeof x never 'number' when x comes from the prompt function?
(4 answers)
Closed 5 years ago.
See code below. My question is, why do I need to use parseInt() on bill and tipPercent for the totalCost calculation when the use actually enters in an integer already?
function billTotal() {
var bill = prompt("How much was your meal?");
if (bill != parseInt(bill)) {
alert("You need to enter an integer");
return;
};
var tip = prompt("How much would you like to tip?");
if (tip != parseInt(tip)) {
alert("You need to enter a number");
return;
}
var tipPercent = bill * (tip / 100);
var totalCost = parseInt(bill) + parseInt(tipPercent);
alert("You're Meal Cost " + totalCost);
};
billTotal();
The result of window.prompt is always a string. You need to use parseInt if you want to work with it as an integer.
Please note that result is a string. That means you should sometimes cast the value given by the user. For example, if his answer should be a Number, you should cast the value to Number. var aNumber = Number(window.prompt("Type a number", ""));
Reference : https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt
Usually, you need parseInt in order to convert a user input (prompt) to an integer and then does arithmetic operations using this value.
As it stated more formally here:
The parseInt() function parses a string argument and returns an
integer of the specified radix (the base in mathematical numeral
systems).
Your code could be refactored like below. Initially we parse the user input and provided that input is valid we proceed with the calculation.
function billTotal() {
var billStr = prompt("How much was your meal?");
var bill = parseInt(billStr,10);
if (!bill || bill < 0) {
alert("You entered an ivalid value for bill");
return;
};
var tipStr = prompt("How much would you like to tip?");
var tip = parseInt(tipStr,10);
if (!tip || tip < 0) {
alert("You entered an invalid value for tip");
return;
};
var tipPercent = bill * (tip / 100);
var totalCost = bill + tipPercent;
alert("You're Meal Cost " + totalCost);
};
billTotal();
I have been looking to validate the data input to check whether it is a integer or a string. I looked around and saw some suggestions and typeof suggestions but nothing seems to work.
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
var mk1 = parseInt(mk1);
mark1.push(mk1);
If you want to check whether input string is not a number try this:
if (isNaN(parseInt(name, 10)) {
//name is String
} else {
//name is Number
}
use the === operator as below
if (mk1 === parseInt(mk1 , 10))
alert("mk1 is integer")
else
alert("mk1 is not an integer. May be String")
If you don't know that the argument is a number-
function isInt(n){
return Number(n)===n && n%1===0;
}
Try this way to find input type;
if(!isNaN(parseInt(mk1)))
// for integer
else if(!isNaN(parseFloat(mk1)))
//for float
else
// String
When you prompt() the user for data, you always get a string. If you want to check, whether it actually contains just a number, you can try this:
var value = prompt('...'),
num = parseInt(value, 10);
if (num == value) {
// ... it is an integer, use `num`
} else {
// ... it's not an integer (or not *just* an integer), use `value`
}
(or use parseFloat(value) for real numbers).
It's hard to say what are you trying to do really. You seem to declare var mk1 twice, which looks a bit strange. Also, even if parseInt fails (then returns NaN [Not a Number]) you add it to mark1, which is probably not what you want. Have a look at this:
var nam = prompt("Enter name:")
person.push(nam);
var mk1 = prompt("Enter mark 1:");
mk1 = parseInt(mk1);
if (Number.isNaN(mk1) === false) {
mark1.push(mk1);
} else {
alert("mark 1 is not a number");
}
Use this function:
isNaN(parseInt(mk1))
It will return "true" if not a number, and "false" if a number