I am trying to make a guessing game that generates a random number which the user guesses. This guessing game must use some kind of loop. Right now it is enclosed in a function that is called when the user clicks a button, and a boolean that limits the number of guesses the user can make.
To my understanding, a loop runs without stopping until its conditions have been satisfied. If I were to have a loop in this situation, the final output would be the loop's last iteration. NumGuesses would have a value of 6 because that was when the loop stopped. How can I replace the conditional with a loop and still have it work?
//Declare variables and constants
var guessesLeft; //number of guesses the user has left
var userGuess; //user's guess
var highLimit = 1000; //high parameter
var numGuesses = 1; //number of guesess the user has guessed
var allowedGuesses = 6; //number of allowed guesses
var NL = "\n"; //new line
//function to be called when the user presses Submit Guess
function guessingGame() {
//random number that is generated
var randNum = Math.floor(Math.random() * highLimit + 1);
if (numGuesses <= allowedGuesses) {
userGuess = prompt("Enter a number between 1 and " + highLimit + ": " , "")
userGuess = parseInt(userGuess);
guessesLeft = (allowedGuesses - numGuesses) + " guesses left.";
//If userGuess is in the specified parameters
//If userGuess is larger than 1 and smaller than the higher parameter
if ((userGuess > 1) && (userGuess < highLimit)) {
//If userGuess does not equal randNum
if (userGuess !== randNum) {
//If userGuess is too low
if (userGuess < randNum) {
//output
document.numForm.gameResults.value = "You guessed too low! Please guess again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You have " + guessesLeft;
}
//If userGuess is too high
else if (userGuess > randNum) {
document.numForm.gameResults.value = "You guessed too high! Please guess again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You have " + guessesLeft;
}//end if
}
else {
//If userGuess is correct
document.numForm.gameResults.value = "You guessed correctly!";
}//end if
}
else {
document.numForm.gameResults.value = "Your guess was out of the specified parameters. Please try again. " + NL + "Your current number of guesses: " + numGuesses + NL + "You currently have " + guessesLeft;
//user may have entered their guess wrong
numGuesses--;
}//end if
//add to number of guesses so the program stops when it reaches the allowed number
numGuesses++;
}//end outer if statement
return false;
}//end guessingGame()
It sounds like the problem statement expects you to block waiting for user input as opposed to triggering a function in response to a DOM event.
Have a look at window.prompt
Placing this in a loop would block the loop until the user responded.
Using prompt() as suggested by retrohacker and a do {} while () loop, the following code demonstrates this in action:
var minNumber = 1;
var maxNumber = 2;
var guessesLeft = 3;
var numberToBeGuessed = minNumber +
(Math.random() * (maxNumber - minNumber + 1) | 0);
var succeeded;
var message = 'Make a guess';
do {
if (prompt(message) == numberToBeGuessed) {
alert('Correct, the number is ' + numberToBeGuessed);
succeeded = true;
} else {
guessesLeft--;
message = 'Try again, ' +
guessesLeft +
' guess' + (guessesLeft > 1 ? 'es' : '') +
' left';
}
} while (!succeeded && guessesLeft)
Related
I want to create a "Guess the numbers game" where you guess a random number within a certain amount of attempts.
I struggle with:
(Must have)
1. Progressing in the loop after the alert (which shows you if your guess was to high, too low, or not a number.
(Nice to have)
2. Resetting the game if you managed to guess the number or ran out of attempts. Resetting means to restore the original amount of guesses and zeroing your attempts. Maybe just a command that refreshes the page.
I'm - after years of break after my first attempts - new to coding.
Here is access to my project: https://glitch.com/~gravel-pyrite
I think this is the relevant loop/conditions engine where I mess up:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
document.getElementById("submit").onclick = function() {
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I expect that after the alerts, I can enter a new value, instead I get stuck in an "alerts loop".
EDIT: I've updated my code now. Reloading the page in after succeeding using up all tries works well.
One thing open:
document.getElementById('feedback').innerHTML = "Remaining guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
won't only show after the first time the button was submitted.
This is the HTML:
<body>
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button onclick="resetGame()">Reset Game</button>
</body>
Adjusted your code
See fiddle example: https://jsfiddle.net/u0cmtg7j/1/
You don't need a loop, do everything in you submit event.
Also move your DOM manipulation code inside your submit event since you want to update the HTML every time your result changes.
Suggestions:
pack you DOM/HTML manipulation code in a function so that is nice and re-usable.
JS
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Prompt that asks user to guess a number between x / 10
//Check if number is correct
//If wrong, prompt them to guess again unti they run out of guesses
//If correct, tell them they won, the number of attempts and thank you
document.getElementById("submit").onclick = function() {
var attempts = document.getElementById("guessInput").value;
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter > maxTries) { //If running outs of attempts, break out of loop
alert("You used up your maximum tries.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
}
function resetGame() {
}
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
HTML
<h1>Guess what!</h1>
<p>Guess a number between <span id="min"></span> & <span id="max"></span></p>
<div>
<label for="guessInput">Your guess</label>
<input type="text" id="guessInput">
<input type="submit" id="submit">
</div>
<p id="feedback"></p>
<p id="guessedNumbers"></p>
<button>Reset Game</button>
There is no need for you to loop within your onclick callback method. By looping you're going to keep checking the value in guessInput without letting the user change their guess, and so the same if block will always run until the player is out of guesses. Instead, you need the click method to control when and how many times the code within your function runs, as it will allow the user to change their guess:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
console.log(randomNumber);
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(attempts);
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
alert("You used up your maximum tries.");
// resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
alert("Awesome! You guessed the number right: " + randomNumber + "You needed " + attempts + " attempts.");
//resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
alert("Your guess " + attempts + " is too low. Guess higer.")
}
}
<input id="guessInput" type="number" />
<button id="submit">Guess</button>
This is my result. I'm sure things can be improved but all works functionally:
var rangeMin = 0; //set the min value
var rangeMax = 10; //set the max value
var randomNumber = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
var counter = 0;
var maxTries = 5;
var remainingTries = maxTries;
var guessedNumbers = [];
//Displaying min, max and remaining guesses in HTML
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax+"!";
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
//The code
document.getElementById("submit").onclick = function() {
var attempts = +document.getElementById("guessInput").value; // use `+` to make sure your input value is treated as a number and not a string
guessedNumbers.push(" "+attempts+" ");
counter++;
remainingTries--;
if (counter >= maxTries) { //If running outs of attempts, break out of loop (test for >= to)
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;alert("You used up your maximum tries. A new game will start.");
resetGame();
} else if (isNaN(attempts)) { //If anything else than a number is entered
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert(attempts + " is not a number");
} else if (attempts == randomNumber) { //If guessed correctly
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Awesome! You guessed the number right: " + randomNumber + ". You needed " + attempts + " attempts.");
resetGame();
} else if (attempts > randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too high. Guess lower.")
} else if (attempts < randomNumber && counter < maxTries) {
document.getElementById('feedback').innerHTML = "Remainig guesses: "+remainingTries;
document.getElementById('guessedNumbers').innerHTML = "Your guesses so far: " + guessedNumbers;
alert("Your guess " + attempts + " is too low. Guess higehr.")
}
}
function resetGame() {
location.reload(true);
}
I saw your question yesterday, I prepared an answer for you but I found that you have deleted your question :) .
I use console.log(someVariable); before using it in my code so that I make sure it exists and not null or undefined
when I did this with your code I found that the variable 'random' existed when I declared it and assign it, but inside the event handler function it becomes 'undefined' because the function is asynchronous
the working code is the following with simplified logic
var rangeMin = 0;
var rangeMax = 10;
var remainingGuesses = 4;
document.getElementById('min').innerHTML = rangeMin;
document.getElementById('max').innerHTML = rangeMax + "!";
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
var random;
var guessesMade = 0;//the user hasn't guessed anything yet os we'll declare and assign the variable as zero
document.getElementById("submit").onclick = function guess() {
//this is a new guess from the user, lets increase the counter of guesses made and decrease remaining guesses
guessesMade++;
remainingGuesses--;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
//lets assign the variable random a number
random = Math.floor(Math.random() * (rangeMax - rangeMin + 1)) + rangeMin;
//lets get what the user guessed
var userGuess = document.getElementById("guessInput").value;
if (random == userGuess) {
alert("CONGRATULATIONS!!! GUESSES NEEDED: " + guessesMade);
//Resetting:
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//So the user didn't guess it right, there two scenarios:
//1- user already consumed his chances, we'll alert him about it and reset the game
//2- user still has guesses to make, we will test and advise him
if (remainingGuesses == 0) {
// scenario (1-)
alert("SORRY, YOUR RAN OUT OF GUESSES. LETS PLAY AGAIN!");
remainingGuesses = 4;
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else {
//scenario (2-)
//we will check the value of his guess and advise him
if (random > userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS SMALLER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A HIGHER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
else if (random < userGuess) {
alert("SORRY, YOUR GUESS " + userGuess + " IS HIGHER THEN THE NUMBER IN QUESTION." + "\n" + "CHOOSE A SMALLER NUMBER");
document.getElementById('feedback').innerHTML = "Remainig guesses: " + remainingGuesses;
}
}
}
}
I am creating a note pad that is to help keep notes consistent between users. I am unable to copy the multiple text boxes to a string. I have attached all of my Java Script.
The copy button that I would like to use to link the multiple text boxes into one string of text. the reset button works at clearing the page and the copy button follows the not empty text box checks. Please help with my copy string to the clipboard.
I have tried a bunch of different sites on the java script with no success. I have also reviewed Stack Overflow to see if I could find a close project.
input type="button" id="BtnSupSubmit" value="Copy" onclick="notEmptySup()" style="width: 87px"
function settime() {
var curtime = new Date();
var curhour = curtime.getHours();
var curmin = curtime.getMinutes();
var time = "";
if (curhour == 0) curhour = 12;
time = (curhour > 12 ? curhour - 12 : curhour) + ":" +
(curmin < 10 ? "0" : "") + curmin + ":" +
(curhour > 12 ? "PM" : "AM");
document.date.clock.value = time;
clock = time
window.status = time
}
function notEmptySup() {
var myTextField = document.getElementById('TxtBoxCallersName');
if (myTextField.value != "") notEmptySup2()
else
alert("Please enter callers name.")
}
function notEmptySup2() {
var myTextField = document.getElementById('TxtBoxSupIssue');
if (myTextField.value != "") notEmptySup3()
else
alert("Please enter the reason for the escalation.")
}
function notEmptySup3() {
var myTextField = document.getElementById('TxtBoxSupAction');
if (myTextField.value != "") notEmptySup4()
else
alert("Please enter the action you took to help the customer.")
}
function notEmptySup4() {
var myTextField = document.getElementById('TxtBoxSupResolution');
if (myTextField.value != "") CreateMessage()
else
alert("Please enter the resolution of the call.")
}
function CreateMessage() {
strMessage =
"Time: " + clock + "\|" +
"***Supervisor Escalation" + "\***|" +
"Caller: " + document.getElementById("TxtBoxCallersName").value + " \| " +
"Reason: " + document.getElementById("TxtBoxSupIssue").value + " \| " +
"Action: " + document.getElementById("TxtBoxSupAction").value + " \| " +
"Resolution: " + document.getElementById("TxtBoxSupResolution").value + " \| " +
"Ticket Number: " + document.getElementById("TxtBoxSupTicketNumber").value + " \| " +
"Addl Notes: " + document.getElementById("TxtBoxSupNotes").value;
document.getElementById("hdnBuffer").value = strMessage;
var buffer = document.getElementById("hdnBuffer").createTextRange();
buffer.execCommand("Copy");
}
Most of what you have is redundant. See comments inline below:
// Get a reference to the form
let frm = document.querySelector("form")
// Set up a sumbit event handler for the form
frm.addEventListener("submit", function(evt){
// Just get the locally formatted time
var message = "Time: " + new Date().toLocaleTimeString() +
"\n***Supervisor Escalation***\n\n";
// Get all the input elements
let inputs = document.querySelectorAll("input");
// Loop over them
for(let i = 0; i < inputs.length; i++){
if(inputs[i].value === ""){
alert("Please enter the " + inputs[i].dataset.message);
inputs[i].focus(); // Put focus on bad element
evt.preventDefault(); // Cancel the form submit
break; // Exit the loop
} else {
// Update the message
message += inputs[i].dataset.message + ": " +
inputs[i].value + " \n";
}
}
alert(message); // Do whatever you want with the message
});
<form action="https://example.com" method="post">
<div><label>Name:<input data-message="callers name"></label></div>
<div><label>Issue: <input data-message="reason for the escalation"></label></div>
<div><label>Action: <input data-message="action you took to help the customer"></label></div>
<div><label>Resolution: <input data-message="resolution of the call"></label></div>
<button type="submit">Submit Ticket</button>
</form>
I need the input field to clear after the user clicks the button to convert the number they've entered. I'm having a difficult time figuring this out, if anyone can help i feel like it's a very simple solution but, I can't seem to wrap my head around it.
(function () {
//Constants
const KM_TO_MILES = 0.625;
const MILES_TO_KM = 1.6;
var user = prompt("So..What's your name beautiful?");
if (user === null) {
alert("NOOOOO, you cancel me? meanie.")
remove();
}
//on load function
window.onload = function () {
var result = document.getElementById("result");
//display the user's name with a message prompt to continue to enter a distance
result.innerHTML = "Okay, " + user + ", enter your distance and I will calculate for you, don't worry.";
document.getElementById("convertBtn").onclick = startConvert;
};
//on load function done
//conversion function
function startConvert() {
var placeholder = document.getElementById("distance").value;
var distanceInput = document.getElementById("distance").value;
var conversion = document.getElementById('List').value;
document.getElementById("List").value;
// If the user doesn't input a number run the alert
if ((placeholder === "") || (conversion == "Select Types")) {
alert("You didn't enter anything mate");
// If the user inputs a number and clicks KM to M then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Kilometers to Miles") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * KM_TO_MILES + " miles.");
// If the user inputs a number and clicks M to KM then calculate it and in the html page change the text to show the answer.
} else if (conversion == "Miles to Kilometeres") {
document.getElementById("result").innerHTML = "Okay, " + user + " ,the distance of " + distanceInput + " is equal to " + (distanceInput * MILES_TO_KM + " kilometers.");
}
}
//conversion function done
}());
document.getElementById('yourid').value = '';
you call this event on your button click surely it'll be works
I'm having problems with this bit of code. For some reason it won't capture the radSize, and it's giving me problems. Any ideas?
The page is supposed to capture the values, then add the base and size together to output total.
$(function() {
$("#btnMessage").click(function() {
var name = $("input[name=txtName]").val();
var phone = $("input[name=txtPhone]").val();
var basePizza = $("#cboBase").val();
var size = $("input[name=radSize]").is(":checked").val;
// alert(name +" "+ phone +" "+ basePizza +" "+ size);
var message = "";
var calculation = parseInt(basePizza) + parseInt(size);
//test each value
if (name == "")
message += "--Enter a first name";
if (phone == "")
message += "\n--Provide a number";
if (basePizza == "0")
message += "\n--Pick Base Pizza";
if (size == "")
message += "\n--Pick a Size";
else
message += name + "," + " " + "Your total for the pizza will be " + "$" + calculation;
alert(message);
// $('#output').html(message);
});
});
This line isn't really valid:
var size = $("input[name=radSize]").is(":checked").val;
The .is(":checked") part is a jQuery filtering utility that will return true or false.
Instead, you want to do something like this:
var size = $("input[name='radName']:checked").val();
Assuming only one of the "radSize" checkboxes can be checked, $("input[name='radName']:checked") will return the checked checkbox and val() will return its value.
Seemed like an easy problem to solve. Cannot figure out why the code will return the secret word despite entering spaces or too many/too few characters. Need a little help. Thanx!
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
<!--variable to hold secret word-->
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
do {
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length < 6) {
window.alert("secret word is too short");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user.prompt.length > 6) {
window.alert("secret word is too long")
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
else if(user_prompt.indexOf('') >= 0) {
window.alert("secret word cannot contain spaces");
var user_prompt;
document.getElementById("guess").innerHTML= text + "<br>" + user_prompt + "<br>" + output;
}
}
while(user_prompt != -999);
}
Apart from the typos you have (user_prompt != user.prompt), you're looking for a 7-character string with no spaces.
What this condition checks:
if(user_prompt.length == 6 && user_prompt.indexOf('') >= 0) {
is a 6-character string with ANY character present.
What you need instead is:
if(user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
This will be true if the string length is 7 and there are no spaces.
Here's a working example, I've simplified it a bit so it's easier to work with in a snippet here, but you can see and reuse the conditions:
function secretWord() {
var text = "You entered";
var output = "Thank you, Po's secret word was validated";
var user_prompt = prompt("Enter Allen's secret word. It must contain exactly 7 characters and there can be no empty spaces", "");
document.getElementById("guess").innerHTML = '';
if (user_prompt.length == 7 && user_prompt.indexOf(' ') == -1) {
document.getElementById("guess").innerHTML = text + "<br>" + user_prompt + "<br>" + output;
} else if (user_prompt.length < 7) {
document.getElementById("guess").innerHTML = "secret word is too short";
} else if (user_prompt.length > 7) {
document.getElementById("guess").innerHTML = "secret word is too long";
} else if (user_prompt.indexOf(' ') >= 0) {
document.getElementById("guess").innerHTML = "secret word cannot contain spaces";
}
}
<div id="guess"></div>
<button onclick="secretWord()">Run</button>
else if(user.prompt.length < 6) {
// ...
else if(user.prompt.length > 6) {
In both cases, user.prompt.length should be user_prompt.length
your problem is in else if statement
it should be user_prompt and not user.prompt
besides, even if you enter space yet exactly right amount of characters say 6 or so, it will pass the first if test.
you are not checking for space i.e. ' ' but ''. see to it you check for spaces properly.