Simplify my isNaN function for two input variables - JavaScript - javascript

i have two variable i am getting through two prompts. One is startNum the other is rangeNum. I am trying to error catch it so that if they are not positive numbers, it will reprompt the user until a postive value is given. Currently i have this working by running an isnan for each vaiable, but im wondering if I can just have one function that checks for both prompts whether the number entered is positive, and also if not, it will reprompt the correct prompt to the user. Thanks in advance for any help/answers.
function isPosNum() {
startNum = parseInt(prompt("Please enter a positive starting value"));
if (isNaN(startNum)) {
return NaN;
} else if (startNum < 0) {
console.log('failed');
alert('That is not a positive number. Please try again and enter a positive number.');
return "negative";
isPosNum();
} else if ( startNum > 0) {
console.log('worked');
//push initial value to the array
numArray.push(startNum);
//enterRange();
return "positive";
} else {
return "zero";
}
function enterRange() {
rangeNum = parseInt(prompt("Please enter a number to determine the range of values."));
if (isNaN(rangeNum)) {
return NaN;
} else if (rangeNum < 0) {
console.log('failed');
alert('That is not a positive number. Please try again and enter a positive number.');
return "negative";
enterRange();
} else if ( rangeNum > 0) {
console.log('worked');
//push initial value to the array
//collatz();
return "positive";
} else {
return "zero";
}
}
}
I was able to get the code working thanks to deamentiaemundi's answer. Here is my final code for those who wish to see.
function getStartNum(){
startNum = parseInt(prompt('Please enter a starting number greater than 0.'));
if(!isPosNum(startNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getStartNum();
} else {
getRangeNum();
}
}
function getRangeNum(){
rangeNum = parseInt(prompt('Please enter a range value greater than 0'));
if(!isPosNum(rangeNum)){
alert("error! That is an incorrect value. Please renter an appropriate positive value.");
getRangeNum();
}
// and so on
}
function isPosNum( number ) {
if (isNaN( number )) {
return false;
} else if (number < 0) {
return false;
} else if (number == 0) {
return false;
} else {
return true;
}
}

Make a function checkRange(number) which takes the number as an argument and returns either true or false depending on that number.
The second function is the one with the prompts in it.
function getNumbers(){
startNum = parseInt(prompt('Please enter a number'));
if(!checkRange(startNum)){
alert("error!");
getNumbers();
}s
rangeNum = parseInt(prompt('Please enter a range'));
if(!checkRange(rangeNum)){
alert("error!");
getNumbers();
}
// and so on
}

Related

JavaScript Recursion exercise: Unexpected token else

I have read about this error on other threads that mostly ask the user to remove semicolons. This seems to have no effect on my code.
function isEven(number){
if (number > 1)
return isEven(number-2);
else if (number == 1)
return false;
else if (number == 0)
return true;
else if (number < 0)
number *= -1
return isEven(number);
else
return "Error";
}
It seems that this line [number *= -1] is causing the error as if I remove it the code runs with no error except for negative numbers where the stack runs out of memory. What I'm trying to do is to make all numbers positive.
Anyone that would like to help me out?
Solution
function isEven(number){
if (number < 0){
number *= -1
return isEven(number);}
else if (number > 1){
return isEven(number-2);}
else if (number == 1){
return false;}
else if (number == 0){
return true;}
else
return "Error";
}
Short answer: Wrap your codes with {}
if (){
..
..
}else {
..
..
}
Long answer :
else if (number < 0)
number *= -1
return isEven(number);
You are not using {} hence the very next line of the condition only considered as a statement belong to the else if and the later will be treated as general statements.
Since you have 2 lines of code in else if, the link broken there and your else became an orphan. That is the reason you seeing the error. Please wrap up your conditions in {}
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1
return isEven(number);
}
else{
return "Error";
}
}
Note: Not only to avoid this specific error but to avoid many other weird things always try to use {}. That makes everyones life easy.
Problem is without curly brackets {}
Better you could add {}(curly brackets) on each if and else statement
function isEven(number) {
if (number > 1) {
return isEven(number - 2);
} else if (number == 1) {
return false;
} else if (number == 0) {
return true;
} else if (number < 0) {
number *= -1
return isEven(number);
} else {
return "Error";
}
}
console.log(isEven(-2))
The problem is that you are trying to execute 2 lines of code in the 3rd else if without wrapping it up in curly braces.
By default only single line gets executed when you don't wrap up the block in curly braces.
function isEven(number){
if (number > 1){
return isEven(number-2);
}
else if (number == 1){
return false;
}
else if (number == 0){
return true;
}
else if (number < 0){
number *= -1;
return isEven(number);
}
else{
return "Error";
}
}

Writing a function that determines if both integers a user enters are odd numbers

How would you write a function that determines if the two numbers a user enters is both odd and returns a boolean value that is true if both numbers are odd? I already know how to write a function that determines if the two numbers a user enters is even or not.
Try:
function bothOdd(num1, num2) {
if (num1 % 2 == 1 && num2 % 2 == 1) {
return true;
}
return false;
}
window.alert(bothOdd(1, 2));
window.alert(bothOdd(1, 1));
That pretty easy and simple
numbersOdd(1,2); // return false
numbersOdd(14, 222); // return true;
function numbersOdd(n1, n2) {
return n1%2 === 1 && n2%2 === 1;
}

Nested else if in javascript

In this random number guessing, after obtaining input from user, if its is wrong (it should go to else) it does not go to the else statement. I can't find where it went wrong.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
var random = Math.floor(Math.random() * 10) + 1;
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}
} else if (guessint < random) {
var guessless = prompt("Try again with value GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}
} else {
document.write("Oops Guessed wrong");
}
Assuming that both guessint and random are indeed defined numbers, then your else condition will never be reached, because when comparing one number against another the only three logical outcomes are that the first is equal, less to, or greater than, the second.
You have obscure { in last else if statement, i've hightlighted it with ___^___ in code snippet below, remove it and everything suppose to work as expected:
else if(guessint<random)
{
var guessless = prompt("Try Again With Valur GREATER than "+guessint)
if(parseInt(guessless)===random)
{
document.write("Guessed Correct Less")
}
}
___^___
else
{
document.write("Oops Guessed wrong");
}
Updated code, you need to have the else inside, updated code below.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !");
guessint = parseInt(guess);
console.log(guessint);
var random = 4; //Math.floor(Math.random()*10)+1;
console.log(random);
if (guessint === random) {
document.write("Guessed Correct");
} else if (guessint > random) {
var guessgreat = prompt("Try Again with value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
document.write("Guessed Correct great");
}else {
document.write("Oops Guessed wrong");
}
} else if (guessint < random) {
var guessless = prompt("Try Again With Valur GREATER than " + guessint);
if (parseInt(guessless) === random) {
document.write("Guessed Correct Less");
}else {
document.write("Oops Guessed wrong");
}
}
You could use a while loop for guessing. Stay in the loop while the input value is not equal to the random value.
Inside the loop, you need to check for greater, then and prompt the user. after promting, you need to convert the value to an integer with base 10.
If the value is smaller (the else part) prompt for a new number.
If the loop id leaved, you know the guessed value is found and display the message.
var guess = prompt("Enter A Value Guessing Between 1 to 10 !"),
guessint = parseInt(guess, 10),
random = Math.floor(Math.random() * 10) + 1;
while (guessint !== random) {
if (guessint > random) {
guessint = parseInt(prompt("Try Again with value LESSER than " + guessint), 10);
} else {
guessint = parseInt(prompt("Try Again With Valur GREATER than " + guessint), 10);
}
}
document.write("Guessed Correct");
Let's go through it step by step.
Let's say random is 10 and the user picks 9 (so guessint = 9).
Now let's replace those values on your if / else statements:
if (9 === 10) { // False!
} else if (9 > 10) { // False!
} else if (9 < 10) { // True!
/* Runs this part of the code */
} else { // It will never get to this else!
}
No matter what value the user selects, it will have to be either:
Equal to 10
Greater than 10
Lesser than 10
There is no number that will not match any of those conditions. So it will always enter one of your if statements, and never the last else.
You would need an else on every if, like Thennarasan said, or a control variable, like so:
var guessint = parseInt(prompt("Guess a value between 1 and 10!"));
var random = Math.floor(Math.random() * 10) + 1;
// Control variable
var guessed_correctly = false;
if (guessint === random) {
// Correct on first chance
guessed_correctly = true;
} else if (guessint > random) {
// Second chance
var guessgreat = prompt("Try again with a value LESSER than " + guessint);
if (parseInt(guessgreat) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
} else if (guessint < random) {
// Second chance
var guessless = prompt("Try again with a value GREATER than " + guessint);
if (parseInt(guessless) === random) {
// Correct on second chance
guessed_correctly = true;
} else {
// Incorrect on second chance
guessed_correctly = false;
}
}
if (guessed_correctly === true) {
// If the user was correct on any chance
document.write("Congratulations!");
} else {
// If the user was incorrect on both chances
document.write("Oops! Guessed wrong!");
}
Alternatively, there are other methods to implement the game you're making with whiles and such, but the example I've given is based on your format.

Javascript - Find if number is positive or negative

I see other solutions to my question but none that help me.
I want to create a function to find if a number is positive/negative. The function should take an integer argument and return true if the integer is positive and false if it is negative.
Also, prompt the user again and again if anything other than a number is entered
Here's the code so far
When I enter a number, it keeps alerting me it is true or false but won't let me enter another.
How do I control my loop so I can ask until -1 is entered? It is not giving me a chance to enter -1
function isPositive(num) {
var result;
if (num >= 0) {
result = true;
} else if (num < 0) {
result = false;
}
return result;
}
var num;
num = parseInt(prompt("Enter a number"));
while (num != -1) {
alert(isPositive(num));
if (isNaN(num)) {
alert("No number entered. Try again");
num = parseInt(prompt("Enter a number"));
isPositive(num);
while (num != -1) {
alert(isPositive(num));
}
}
}
There's a few things wrong with your code, so here's a rewrite with comments:
function isPositive(num) {
// if something is true return true; else return false is redundant.
return num >= 0;
}
// when you want to keep doing something until a condition is met,
// particularly with user input, consider a while(true) loop:
var num;
while (true) {
num = prompt("Enter a number");
// check for null here
if (num === null) {
alert("No number entered. Try again.");
continue; // return to the start of the loop
}
num = parseInt(num, 10); // second argument is NOT optional
if (isNaN(num)) {
alert("Invalid number entered. Try again.");
continue;
}
// once we have a valid result...
break;
}
// the loop will continue forever until the `break` is reached. Once here...
alert(isPositive(num));
Math.sign(number)
which returns either a 1, -1 or 0
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
The number 0 is neither positive, nor negative! :P
function isPositive(num)
{
if(num < 0)
return false;
else
return true;
}
Or a simple way,
function isPositive(num)
{
return (num > 0);
}
You are testing if it isn't -1. Try this:
if(num < 0){
...IS NEGATIVE...
}else{
...IS POSITIVE...
}
This checks if it is less than or greater than 0.

Validate that input is between 2 numbers in javascript

I am currently using Google maps and attempting to use input validation. I require the user to use a number between 0 and 20 to set as a zoom on my location.
Below is the code I am using. The first if statement works perfectly for any number over 20 but the second does not work when I use numbers like 0 and -1 (for instance.)
Any suggestions for fixing this?
function inputIsValid() {
console.log("Inside inputIsValid function");
//Check for Above 20
if (document.getElementById("txtZoom").value > 20) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
//Check for Number below 0
if (document.getElementById("txtZoom").value < 0) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
}
}
}
The problem is you nested the second check within the first, so it will never be reached. Try this:
function inputIsValid() {
var zoomValue = document.getElementById("txtZoom").value;
if (zoomValue > 20 || zoomValue < 0) {
alert("Please insertAmount between 0 and 20");
document.getElementById("txtZoom").focus();
return false;
}
}
function inputIsValid() {
$value = document.getElementById("txtZoom").value;
if (($value < 0) && ($value > 20)) {
alert("Please enter a value between 0 and 20");
return false;
}

Categories

Resources