Trying to break from loop in Javascript - javascript

Im trying to practice loops in Javascript. I have a program that asks for the temperatures for the last week then works out its average and prints a text depending on the results. I have added into it to return an error if the number entered is not between -30 and 40 and stop the loop. This works ok apart from I still get the other text based on the average. I understand that using break like I am will still continue the rest of the code after the loop which is why Im getting the other text still. I am just starting out in the basics so it should be as simple as possible. How can I do it so as not to get the other text, what should I be using instead?
<meta charset="UTF-8">
<title>Lämpötilat</title>
<script language="JavaScript">
var lampotila=0;
var i;
for (var i = 0; i < 7; i++) {
lampotila = Number(prompt("Enter the temperatures for the last 7 days"));
if(lampotila <-31 || lampotila > 40) {
document.write ("ERROR: You must enter a temperature between -30° and 40°");
{break;}
}
}
yht = yht + lampotila;
k = yht / 7
ki = k.toFixed(2);
if (ki < -10) {
document.write ("Kylmää talvisäätä!");// cold winter weather
}
else if (ki <0 && ki> -10) {
document.write ("Hyvä hiihtosää!");// good skiing weather
}
else if (ki >0 && ki <10) {
document.write ("Kevät tulossa!");// spring is coming
}
else {
document.write("T-paita vois riittää!");// t- shirt should be enough
}
</script>

Increasing the indentation may help making the code more readable and easier to detect errors and bugs.
From http://www.w3schools.com/js/js_break.asp we know that break; lets us get out of a loop. So, after the break no more iterations will be made inside that loop and the computer will continue executing what is after that loop.
Your second part of the code is outside the loop, so doing break in the loop will not affect the rest. You could have a variable that indicates if an error was found while inputting data. If so, then don't execute the rest of the code.
Something like this:
var lampotila=0;
// var i; <= You don't need this if you `var i=0` inside the foor loop.
// Also, you don't use i outside the loop so there is no need
// to have it declared in the global scope.
var error = false; // <== THIS LINE NEW
for(var i=0; i<7;i++){
lampotila=Number(prompt("Enter the temperatures for the last 7 days"));
if(lampotila <-31 || lampotila > 40) {
document.write ("ERROR: You must enter a temperature between -30° and 40°");
error = true; // <== THIS LINE NEW
break;
}
}
if (!error) { // <== THIS LINE NEW
yht=yht+lampotila;
k=yht/7
ki=k.toFixed (2);
if (ki < -10){
document.write ("Kylmää talvisäätä!");// cold winter weather
}
else if(ki <0 && ki> -10) {
document.write ("Hyvä hiihtosää!");// good skiing weather
}
else if (ki >0 && ki <10) {
document.write ("Kevät tulossa!");// spring is coming
}
else {
document.write("T-paita vois riittää!");// t- shirt should be enough
}
} // <== THIS LINE NEW

You can decrease i value before break. So, user must enter true temperature value.
if(lampotila <-31 || lampotila > 40) {
document.write ("ERROR: You must enter a temperature between -30° and 40°");
i = i - 1;
continue;
}}

You have a syntax error in the below line:
{break;}
Try this:
for (var i = 0; i < 7; i++) {
lampotila = Number(prompt("Enter the temperatures for the last 7 days"));
if (lampotila < -31 || lampotila > 40) {
document.write("ERROR: You must enter a temperature between -30° and 40°");
break;
}
yht = yht + lampotila;
k = yht / 7
ki = k.toFixed(2);
if (ki < -10) {
document.write("Kylmää talvisäätä!"); // cold winter weather
} else if (ki < 0 && ki > -10) {
document.write("Hyvä hiihtosää!"); // good skiing weather
} else if (ki > 0 && ki < 10) {
document.write("Kevät tulossa!"); // spring is coming
} else {
document.write("T-paita vois riittää!"); // t- shirt should be enough
}
}

Related

Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();

Functions and else ifs

I'm still pretty new to JavaScript and need to be pointed in the right direction on a tiny project that is just for practice.
Very sorry if I'm not posting incorrectly, this is my first post on Stack Overflow and any help is appreciated.
I've tried accomplishing my goal a few different ways and haven't gotten there.
attack.addEventListener("click", function(){
hit();
});
function hit(){
if (bossHealth.textContent > 0 && playerFocus.textContent >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (bossHealth.textContent >= 0 && playerFocus.textContent < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
strong.addEventListener("click", function(){
bigHit();
});
function bigHit(){
if(bossHealth.textContent > 0 && playerFocus.textContent >= 5){
playerFocus.textContent -= 6;
bossHealth.textContent -= 6;
console.log("strong attack");
}
else if (playerFocus <5){
alert("Strong attack costs 5 focus, if you do not have enough focus try regenerating for a turn");
}
else (bossHealth.textContent <= 0){
bossHealth.textContent = "Dead";
alert("You've killed the bad guy and saved the world!!!");
}
};
easy.addEventListener("click", function(){
reset();
});
function reset(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 10;
};
hard.addEventListener("click", function(){
hardMode();
});
function hardMode(){
playerHealth.textContent = 10;
playerFocus.textContent = 10;
bossHealth.textContent = 15;
};
With function hit I don't get the alert in my else if statement
with function bigHit I also don't get my alert for the else if statement and neither part of the else statement works.
also subtraction works in my functions, but when trying to add another function that uses addition in the same way it adds the number to the end of the string instead of performing math
You really shouldn't depend on what is in the DOM for logic. You should try with local variables then update the DOM based on those variables.
var boss = {}
var player = {}
function reset(){
player.health = 10;
player.focus = 10;
boss.health = 10;
update()
};
function hit(){
if (boss.health > 0 && player.focus >=2) {
player.focus -= 2;
boss.health -= 3;
console.log("attack");
} else if (boss.health > 0 && player.focus < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
update()
}
function update() {
playerFocus.textContent = player.focus
playerHealth.textContent = player.health
bossHealth.textContent = boss.health
}
Your issue is caused by textContent automatically turning your numbers into strings, by managing the data using your own variables this doesn't affect your code's logic.
Alternatively you could parse the strings as numbers using new Number(playerFocus.textContent), parseFloat(playerFocus.textContent), or +playerFocus.textContent but your code will become very hard to read very quickly.
Hope this enough to help you to make more edits to your code.
It looks like your playerFocus variable is a DOM node? Based on that assumption, your condition is missing a check for its textContent:
if (bossHealth.textContent > 0 && playerFocus.textContent >= 5){
// ...
}
else if (playerFocus.textContent <5){
// ...
In JavaScript, else blocks cannot have conditions, so if you want to conditionally check whether bossHealth.textContent <= 0 at the end of your bigHit function, you will need to change it to an else if (bossHealth.textContent <= 0) { ... } block instead.
I'm adding on to #LoganMurphy's comment and my own. In order to use the value of bossHealth it needs to be an integer. Change your code to look something like this:
function hit(){
if (parseInt(bossHealth.textContent) > 0 && parseInt(playerFocus.textContent) >=2) {
playerFocus.textContent -= 2;
bossHealth.textContent -= 3;
console.log("attack");
}
else if (parseInt(bossHealth.textContent) >= 0 && parseInt(playerFocus.textContent) < 2){
alert("Attack costs 2 focus, try regenerating this turn to gain focus and health!");
}
};
https://www.w3schools.com/jsref/jsref_parseint.asp

Number guessing game, relationship between maxGuesses and guess count is skewed by 1

I am trying to let the game only let the user have 3 guesses to guess correctly. The problem is that it lets the user guess a 4th time, but even if user guesses correctly on 4th attempt I get a wrong answer message. I tried changing the number of guesses, changing that i = 0 start position, subtracting one from maxGuesses in the for loop. No matter what I try the relationship is off by one. Here is my code so far.
let readlineSync = require("readline-sync");
let hint = "";
let maxGuesses = 3;
const maxRange = 10;
const minRange = 1;
let userGuess = readlineSync.question(
"I have chosen a number between " +
minRange +
" and " +
maxRange +
". You have " +
maxGuesses +
" tries to guess it!\n"
);
const randomNumber = Math.floor(Math.random() * maxRange + 1);
function handleGuess(userGuess) {
if (userGuess != null && userGuess != undefined && (userGuess <= maxRange && userGuess >= minRange)) {
for (i = 0; i <= maxGuesses - 1; i++) {
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
return;
} else {
if (userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
}
console.log("Dude...YOU SUCK!");
return;
} else {
userGuess = readlineSync.question("Fix your answer fool! \n");
handleGuess(userGuess);
}
}
I assume your first call is handleGuess() with no parameter.
Then, your program asks the user for its first guess (withe the message "Fix your answer fool!"). If you call handleGuess() with a parameter, the following still applies.
After that, the loop will begin.
if the first answer is wrong, the console will display the message "Think [higher/lower] you fool.", and then request the second guess. Still in the first loop iteration.
Do you see where the problem is ?
If the second guess is still wrong, the console will display the second wrong message and request the third guess while still being in the second loop iteration.
Finally, If the third guess is still incorrect, the third "wrong" message will appear and your code will request a fourth guess before ending the loop and display the message "Dude...YOU SUCK!" without verifying your input.
To prevent that, you can do something like this :
function handleGuess(userGuess) {
i = 0;
do {
if(i > 0) {
if(userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
while(isNaN(userGuess)) {
userGuess = readlineSync.question("Correct you guess. \n");
}
} while(userGuess != randomNumber && i < maxGuesses);
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
} else {
console.log("Dude...YOU SUCK!");
}
}
Just set the condition for your loop to be i < maxGuesses not i <= maxGuesses -1:
var maxGuesses = 3;
for (i = 0; i < maxGuesses; i++) {
console.log("Guess " + (i + 1)); // Only adding 1 here so output is 1-based
}

Fizz Buzz Solution: Unexpected Token Function?

I'm having some frustration with this code. I may not be seeing it.
I keep getting either an "Unexpected Token" or "ILLEGAL" error (the latter which completely preplexed me, considering I've never seen an error like that before in my life.
I've been double checking the syntax and I'm thinking it may be something I'm just not catching?
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) {
4 print ("fizz")
5 }
6 if (n%5===0) {
7 print ("buzz")
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i];
11 }
12 }
13 }
14
15
16 fizzBuzz(100);
I'd be thankful for the help! <3
You need some changes:
remove line numbers,
check first for 'fizz buzz' value and use console.log for output. Then use continue statement for jumping to top for next loop,
use i instead of n for checking.
function fizzBuzz(n) {
for (i = 0; i <= n; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("fizz buzz");
continue;
}
if (i % 3 === 0) {
console.log("fizz");
continue;
}
if (i % 5 === 0) {
console.log("buzz");
continue;
}
console.log(i);
}
}
fizzBuzz(100);
function fizzBuzz(n) {
2 for (i = 0; i<=n; i++) {
3 if (n%3===0) { You're checking if the maximum number (n) is divisible by 3.
4 print ("fizz") You should be checking i.
5 }
6 if (n%5===0) { You're checking if the maximum number (n) is divisible by 5.
7 print ("buzz") You should be checking i.
8 }
9 if (i%3 !== 0 && i%5 !== 0) {
10 return [i]; You're returning an array with a single element: i.
11 } You should print i instead.
12 }
13 }
14
15
16 fizzBuzz(100);
The line numbers are what's causing the "ILLEGAL" error. Remove them.
print in JavaScript opens the print dialog to literally print paper out of a printer. Use console.log
If a number is divisible by both 3 and 5, fizzbuzz should be printed. Your code prints fizz and buzz on separate lines.
Working version ( https://www.youtube.com/watch?v=QPZ0pIK_wsc ) :
function fizzBuzz(n) {
for (var i = 0; i <= n; i++) {
var printVal = "";
if (i % 3 === 0) {
printVal += "fizz";
}
if (i % 5 === 0) {
printVal += "buzz";
}
if (printVal === "") {
printVal = i;
}
console.log(printVal);
}
}
fizzBuzz(100);
Lets decrease number of if statements, I have seen many fizzbuzzs - I would like to try another approach
const fizzBuzz = (i = 0, ret) => {
while (++i, ret = '', i <= 100) {
if (i % 3 === 0) {
ret += `fizz`
}
if (i % 5 === 0) {
ret += `buzz`
}
console.log(ret || i)
}
}
fizzBuzz()
The most important part is console.log(ret || i) - empty string is falsy value, so console will log ret if there is some value or current i value
If you're trying to print to your browser's console, use console.log() instead of print(), since print() will open the printer preview in a browser. I'm using Chrome. Remember to check the console by pressing F12 and clicking on "console" in case you've created a html file that includes your javascript script.
Since you are iterating i until it reaches the value of n, you if statements should look like:
if(i%3===0){
// your code...
}
Based on your code, it seems like you want to check for a value that is not a multiple of 3 && a multiple of 5. However, the fizzbuzz challenge requires to print fizzbuzz when encountering a number that is both a multiple of 3 && a multiple of 5. So, you'll need to add the following condition:
if (i%3 === 0 && i%5 === 0) {
console.log("fizzbuzz");
continue; /* Continue may or may not be necessary depending on your program's logic. Continue allows to re-enter the loop
without checking for the remaining if statements. If you use continue, this condition must be the first if statement inside the loop */
}
Your function doesn't need to return anything, since you're using console.log() to visualize the values in each loop iteration. That's why you need to change return [i] for console.log(i).
Don't give up and keep trying!
If you have further questions, I'll be glad to help you.

The score in my JavaScript quiz application it not storing properly. What is wrong with the syntax?

The majority of the code seems to be working. The problem is that it keeps returning the error message that I set in the if statement for calculating the final score message as the final else clause. I'm not sure how to see the value of what is actually being stored in the variable at any given time while the application is running.
var score = 0; // to store the correct answers
//List of answers
var answerOne = 'BLUE';
var answerTwo = 'GREEN';
var answerThree = 'PRINCIPLE';
var answerFour = 'MONEY';
var answerFive = 'WILLY WONKA';
// The questions and their verification protocol
var questionOne = prompt('What is the color of the sky?');
//Conditional statement matching user input to correct answer.
if (questionOne.toUpperCase === answerOne) {
score+= 1;
}
var questionTwo = prompt('What is the color of grass?');
//Conditional statement matching user input to correct answer.
if (questionTwo.toUpperCase === answerTwo) {
score+= 1;
}
var questionThree = prompt('What is the most powerful force?');
//Conditional statement matching user input to correct answer.
if (questionThree.toUpperCase === answerThree) {
score+= 1;
}
var questionFour = prompt('What makes the world go round?');
//Conditional statement matching user input to correct answer.
if (questionFour.toUpperCase === answerFour) {
score+= 1;
}
var questionFive = prompt('Who can take a sunrise and sprinkle it with dew?');
//Conditional statement matching user input to correct answer.
if (questionFive.toUpperCase === answerFive) {
score+= 1;
}
//Final score-providing message to user
if (score = 0) {
alert('Wow, you suck. No crown for you! You had ' + score + 'correct answers!');
} else if (score <= 2 && score > 1) {
alert('You were not the worst, but certainly not the best. You earned a bronze crown with ' + score + ' correct answers!');
} else if (score <= 4 && score > 3) {
alert('You did a pretty good job! You earned a silver crown with ' + score + ' correct answers!');
} else if (score === 5) {
alert('Congratulations! You have successfully answered all questions correctly! You have earned a gold crown with ' + score + ' correct answers!');
} else {
alert('ERROR!')
}
There are a number of issues with this code.
1) toUpperCase is a string function and should be used like:
if (questionFour.toUpperCase() === answerFour) {...
2) In your if/then statement your are assigning 0 to score, not checking that score equals 0. To do that:
if (score === 0) {
3) Finally you need to watch your if/then condition ranges.
This doesn't check if score is 1:
(score <= 2 && score > 1)
This does check if score is 1:
(score >= 1 && score <= 2)
Here's the corrected code.
toUpperCase is a method and, as such, should be written per this example:
questionOne.toUpperCase()
you used assignment operator not the ==.
if(score==0)
to see the value of score add console.log(score) above that.

Categories