My switch
statement is not working properly when analysing a string variable.
The output and input are both <textarea>
's.
HTML
<form name="interface">
<textarea name="output" rows="20" cols="100"></textarea><br>
<textarea name="input" rows="1" cols="100" onKeyDown="thinkInput(event);"></textarea>
</form>
JavaScript
function thinkInput(e)
{
if (e.keyCode == 13)
{
sInput = document.interface.input.value;
document.interface.output.value += sInput;
aInput = sInput.split(" ");
switch (aInput[0])
{
case "say":
textOut("You say \""+sInput.substring(aInput[0].length + 1)+"\"");
break;
case "move":
move(aInput[1]);
break;
default:
thinkFail();
break;
}
document.interface.input.value = null;
alert(aInput[0]);
}
}
I can see in my alert()
at the end that the case is either "say" or "move".
The first time I try to "say mudkipz" or "move around", everything works as I want it, but after that everything I type, thinkFail()
fires.
Yes, we can use a switch statement with Strings in Java.
String is the only non-integer type which can be used in switch statement.
In addition to if...else , JavaScript has a feature known as a switch statement. switch is a type of conditional statement that will evaluate an expression against multiple possible cases and execute one or more blocks of code based on matching cases.
JavaScript Switch vs If Statement Switch statements are cleaner syntax over a complex or stacked series of if else statements. Use switch instead of if when: You are comparing multiple possible conditions of an expression and the expression itself is non-trivial. You have multiple values that may require the same code.
Your code isn't executing due to a new line that appears above the command prompt and the split array doesn't contain the reference first word on [0] value. Don't know why, even though you're clearing the value of input.
Since you'll be needing only one line on this input, I suggest using <input type="text" onKeyDown="thinkInput(event);"/>
to avoid getting new lines on enter.
JavaScript
this.thinkInput = function (e)
{
...
if (e.keyCode == 13)
{
/* Prevent submitting form on Enter */
e.preventDefault();
var command, commands;
command = cmd.value;
commands = command.split(' ');
/* Clear input field */
cmd.value = '';
/* commands[0] will always have reference
to the first word in textfield */
switch (commands[0])
{
...
}
}
}
Here is a little fiddle I threw together from your code: http://jsfiddle.net/npx86/1/
Hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With