I'm working on conditional statements in js. But ran into 2 problems with this script.
1) regardless of user input, the script doesn't process the else clause.
2) my alert method prints first the if alert(), then secondly an undefined alert(). Idk why this is.
<script>
function temperature (temp)
{
var message="";
var temp = 70;
if(temp <= 69) {
alert(message = "Turn on the heat.");
} else {
alert(message = "It is hot enough.");
}
}
</script>
Then my body script is:
<script>
var myTemp=prompt("Please enter your current temperature."); //prompt is ok
//alert fails to process else clause and then prints an undefined alert()
alert(temperature(myTemp));
</script>
I have tried removing the alerts from the function itself. That, however, kills my prompt.
PS I use Sublime 3 with jshint but this problem is out of jshint's jurisdiction, obv.
Please advise and thanks all.
you are using 2 alerts: one inside the another.. and also resetting your temperature value.
Use this:
function temperature (temp)
{
if(temp <= 69) {
return "Turn on the heat.";
} else {
return "It is hot enough.";
}
}
A couple of things:
1) You are setting the variable temp to 70, so it overrides your input.
2) The prompt() function returns a string, which you are then passing into your temperature function where you are trying to compare it to integers. Use parseInt().
3) You are also nesting alerts since you put temperature() in an alert and your temperature() function itself also creates alerts. Choose one or the other.
This is how I'd change it.
<script>
function temperature (temp){
var message="";
var temp = temp || 70;
if(temp <= 69) {
message = "Turn on the heat.");
} else {
message = "It is hot enough.");
}
return message;
}
</script>
and then:
...
alert(temperature(parseInt(myTemp)));
...
Related
I am trying to write a function that gives a user 4 choices, does what they choose and then asks them the first 4 choices again and again until they exit.
I have tried using an if/else loop inside a while loop, but that just takes the first user input and loops at that point. It also concatenates the balance when I try to add the two numbers. I assume that due to the fact that the prompt is a string and assigns a string to the variable. I am using console.log() to try and see what is happening while everything is running, but to no avail.
Sorry if this is a lengthy post and redundant.
let balance = 0;
let deposit = 0;
let withdraw = 0;
function bankFunction (banked) {
alert('Hello, how can I help you today?');
let input = prompt('Q to quit the application \nW to withdraw \nD to deposit \nB to view balance');
while (input != 'Q') {
if (input === 'W') {
withdraw = prompt("Withdraw how much?");
console.log(withdraw);
balance = balance - withdraw;
console.log(balance);
} else if (input === 'D') {
deposit = prompt("Deposit how much?");
console.log(deposit);
balance = balance + withdraw;
console.log(balance);
} else {
alert("done");
break;
}
}
}
If you want to continuously prompt the user for inputs, then the prompt function should be inside your loop too. The essential pseudo code is: "While the input is not "Q", continue to prompt for a user choice".
Implementation:
let input = "A" // Initial input to get the loop working
while (input !== "Q") {
// Get actual user input
input = prompt("Choose Q or W or D or B");
if (input === "W") {
// Withdraw logic
}
else if (input === "D") {
// Deposit logic
} else if (input === "B") {
// ...
}
}
Note that there is a bit of a little gimmick here: I needed to have an initial input ("A") to get the first round of the loop working - since in the first round of the loop, user input has not been received yet. Once it get past that initial first round, the input variable is being continuously re-assigned through the user prompt, and the loop will exactly how the pseudo-code described it.
If you don't like that gimmick, there is another way, called the While-True-Break loop. The essential idea is that: The loop will automatically run forever, until you explicitly stop it (via break statement)
let input;
while (true) {
input = prompt("Choose Q or W or B or D");
if (input === "Q") {
// Stop the program loop
break;
} else if (input === "W") {
// ...
} else if ...
}
I'm not a programmer by any means. I'm an animator trying to use JS expressions in After Effects. I'm getting an "Undefined value used in expression" error on line 1 where I define a variable.I already showed it to my friend on discord who is a cs major, and he had no clue what was wrong with it.
Here's just a paste of the code if you need it:
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1
if (count % 2 == 0){
thisProperty = 95
} else {
thisProperty = 20
};
} ;
Ok I don't know why the hell this fixed it, but I changed the name of the variable from "count" to just "x" and it works now. Go figure
Try it.
var count = 1;
if (framesToTime(time) % 12 == 0) {
count = count + 1;
if (count % 2 == 0){
thisProperty = 95;
} else {
thisProperty = 20;
}
}
thisProperty;
In your code, thisProperty has become an ordinary variable. If you write its name at the end of the code, then its value will be assigned to the property.
In AE, if there is nothing inside an if statement or the if statement contains malformed/error code you will receive this error. Put a temp value inside the curly braces or something to process and ensure nothing inside will throw an error.
I also received this error with this:
pastTime = timeToFrames(time)-1;
curPos = transform.xPosition;
pastPos = transform.xPosition.valueAtTime(framesToTime(pastTime));
if (curPos-pastPos[0] != 0) {
// Here is the problem in my case. added a value here 99 to fix until finished testing.
}
else {
effect("Angle Control")("Angle")
}
if/else statements are strict
The syntax for if/else statements is strict in the JavaScript engine
and need to be written for standardized JavaScript.
https://helpx.adobe.com/after-effects/using/expression-language-reference.html*
I got this error because there was a missing semicolon.
My game here is a guessing game, which counts the number of guess and does not include any repeated guesses.
I am trying to pass the variable tries from function attempts to function tries but it will not work. The count remains 0, but when I pass sameGuess.length it work, why is this?
let random = Math.round(Math.random()*100);
let guess = false;
let sameGuess = []
let tries = sameGuess.length;
function game(){
while (guess === false){
let myGuess = prompt('Guess a number between 0-100:');
numCheck(myGuess);
if (myGuess == random){
guess = true;
repeats(myGuess, sameGuess);
attempts(tries, sameGuess);
}else if (myGuess < random){
repeats(myGuess, sameGuess);
alert('Your number was too small, try again!');
guess = false;
}else if (myGuess > random){
repeats(myGuess, sameGuess);
alert('Your answer was too big, try again!');
guess = false;
}
}
}
function attempts(tries, sameGuess){
if (sameGuess.length == 1){
alert('Well done, you got it frist try!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length <= 15){
alert('You took ' + sameGuess.length + ' tries');
alert('Well done, you didn\'t take too many tries!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}else if (sameGuess.length >=16){
alert('You took ' + sameGuess.length + ' tries');
alert('You got it, but lets see less tries next time!');
document.write("<h1>GUESSING GAME</h1><p>Thank you for playing the Guessing Game <br> Created by Jonathan Fox</p>");
}
}
function repeats(myGuess, sameGuess){
if ((sameGuess.indexOf(myGuess)) == -1){
(sameGuess.push(myGuess));
}else alert('You have already guessed that number! - Dont worry, i haven\'t counted it!');
}
function numCheck(myGuess){
if (isNaN(myGuess)){
alert('Enter a number, don\'t try and be sneaky!');
}
}
game ();
When you access array.length, that value is copied, meaning it won't update even after you add a value to the array:
var array = [];
var length = array.length;
console.log(length); // 0
array.push('Some value');
console.log(length); // Still 0, since it was copied, it is _not_ a reference to the live value
console.log(array.length); // 1, this is a live reference to the length of the array
As it stands now, your code works fine, although it looks like you can remove the tries aspect of it and use the sameGuess.length directly, as you are now.
See this post for more discussion on Pass by Reference or Pass by Value.
You should put tries = sameGuess.length; inside of your while!
I have started javascript today. Trying with the very basic and got stuck with If Else loop.
var input = prompt("type your name"); //variable stores the value user inputs
var outout = tostring(input); // the input value is changed to string datatype and stored in var output
alert(output);//supposed to display the value which it doesn't
if(output == "Tiger")
{alert("It is dangerous");
}
Else
{alert("all is well");
}//I only get a blank page
If I omit the line var output = tostring(input) and try to display the alert box with input value I get the alert box. But after that I only get a blank page. The If Else loop doesn't work at all. I am using notepad++. Also checked in Dreamweaver. There is no compile error. What am I doing wrong?
Sorry for such a basic question and thanks for replying.
Regards,
TD
Your line
tostring(input);
Should be
toString(input);
The toString() method has a capital S
Also, your output variable is called "outout". Don't know if that's a typo...
Not only that, your Else should also have a small e. All JavaScript keywords are case sensitive.
You do not have to convert the result of a prompt to a string, it is a string already. And it actually would be
input.toString()
And Else is lowercase, the correct would be else.
So you can use like this
var input = prompt("Type your name");
if (input == "Tiger")
{
alert("Wow, you are a Tiger!");
}
else
{
alert("Hi " + input);
}
Notice that if you type tiger (lowercase) you will end up on the else. If you want to compare a string case insensitive you can do this:
if (input.toLowerCase() == "tiger")
Then even tIgEr will work.
Your code has the following problems:
var input = prompt("type your name");
var outout = tostring(input);
// Typo: outout should be output
// tostring() is not a function as JavaScript is case-sensitive
// I think you want toString(), however in this context
// it is the same as calling window.toString() which is going to
// return an object of some sort. I think you mean to call
// input.toString() which, if input were not already a string
// (and it is) would return a string representation of input.
alert(output);
// displays window.toString() as expected.
if(output == "Tiger")
{alert("It is dangerous");
}
Else // JavaScript is case-sensitive: you need to use "else" not "Else"
{alert("all is well");
}//I only get a blank page
I suspect what you want is this:
var input = prompt("type your name");
alert(input);
if (input === "Tiger") {
alert("It is dangerous");
} else {
alert("all is well");
}
What is the best practice when counting the number of times an action has been carried out in javascript? for example I have a prompt that asks for a number
var playerGuess = prompt("What is your guess ");
What i would like to do is after 3 attempts end the game with another prompt.
What I am having difficulty with is actually counting the number of inputs
Thanks
I have tried creating a function do count the number of times an input has been made
var guessCount = playerGuess.count;
function limit(playerGuess){
if (guessCount >= 3){
alert("game over");
} else{
alert("carry on");
}
}
totally wrong i know but having a go
Like so:
// Global var to hold number of guesses
var guessCount = 0;
// Function to get the guess
function getGuess() {
// Get a new guess
var guess = prompt('What is your guess ');
// Process guess here, eg:
if (...whatever tests you want to make...) {
// Good guess
alert('Good guess: ' + guess);
} else {
// Bad guess
guessCount += 1;
// Fail out if too many guesses have been tried
if (guessCount >= 3) {
alert('Game over');
return;
}
}
};
Cheers!
You should evaluate the answer you get each time.
If the answer is valid, take the count in another variable and when the count reaches the desired amount take no inputs.
var attempts = 0;
function ask_question(){
if(attempts > 3)
{
// you have played enough!
return;
}
else
{
var playerGuess = prompt("What is your guess ");
if(parseInt(playerGuess) != NaN && playerGuess != '')
{
attempts++;
// do whatever you would like to do with playerGuess
}
}
}
You could do this with a while loop and a variable to store the current iteration. Consider the following, which gives you three chances to guess the "secret" number:
var secretNumber = 42,
youWon = false,
i = 0;
while (i < 3) {
var playerGuess = prompt("What is your guess?");
if (playerGuess == secretNumber){
youWon = true;
break;
}
i++;
}
if (youWon) {
alert("You got it!");
} else {
alert("Sorry, you have no more tries left.");
}
This code loops over and over, incrementing i each time. It asks the question, and checks the answer. If the answer is right, it sets the youWon flag and breaks out of the loop, ending it early. Otherwise, the loop ends naturally after 3 iterations. After the loop is done, the youWon flag is checked to determine if the loop ended because the right answer was given, or if it ended because the number of tries was exhausted.