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
}