Unexpected Identifier fix - javascript

I dont understand what the error means. "Unexpected Identifier". It doesnt really give me any information on the error. I have gotten this error before and I know its probably an error in the code or the way I wrote it. Help please.
<html>
<body>
<script type="text/JavaScript">
// Declare variables
var cardCat; // card category M=morning, A=afternoon, E=evening
var userInput; // user input of cards
var morCard = 0; // morning cards
var aftCard = 0; // afternoon cards
var eveCard = 0; // evening cards
var BR = "</ br>"
var ES = ""
// welcome user, start loop, and ask for card category
document.write("Welcome to Coffee Survey" +BR);
cardCat = prompt("Enter the category of the batch (M, A, or E) or enter Q to quit: " + ES);
userInput = prompt("Enter number of cards in the batch");
// start loop
while (cardCat != "Q") {
if(cardCat == "M")
{ morCard = morCard + userInput; }
else if (cardCat == "A")
{ aftCard = aftCard + userInput; }
else if (cardCat == "E")
{ eveCard = eveCard + userInput; }
};
// Display totals
document.write("Total # of morning cards: " + morCard + BR);
document.write("Total # of afternoon cards: " + aftCard +BR);
document.write("Total # of evening cards: " + eveCard + BR);
//End program
document.write("Thank you for using Coffee Survey");
</script>
</body>
</hmtl>

javascript will be
while (cardCat != "Q") {
document.write("Enter number of cards in the batch");
if(cardCat == "M")
{mornCard = mornCard + userInput; }
else if(cardCat == "A")
{ aftCard = aftCard + userInput; }
else if(cardCat == "E")
{ eveCard = eveCard + userInput }
document.write("Enter category(M, A, or E) or enter Q to quit:);
};
Thing look wrong in your code is placment of End If so correct will be, this is VBSCRIPT not javascript
// start loop
while cardCat != "Q" {
document.write("Enter number of cards in the batch");
If cardCat == "M" Then
mornCard = mornCard + userInput;
Else If cardCat == "A" Then
aftCard = aftCard + userInput;
Else If cardCat == "E" Then
eveCard = eveCard + userInput;
End If'correctly placed end if which is wrong in your code
}
document.write("Enter category(M, A, or E) or enter Q to quit:);
End while

Related

Parameter being set to undefined

I am working on a school project which is based on the game Wheel of Fortune. Currently, I am working on having the computer differentiate between a consonant and vowel, and adding to the player's balance if they correctly guess a letter. As of now, I have encountered two problems.
First, when checking if a letter is a vowel, it correctly says which is which, and also checks if a vowel CAN be guessed (player needs to have at least a certain amount of money). If they can, it will deduct the necessary amount and move on normally. If not, however, it should disregard the guess and have the player guess again. This works until the player guesses a different letter. What happens is the second guess that the player tries is checked, but the first guess, the vowel which they could not afford, is also checked.
Here is what it looks like:
The word is CANADA
Basically, the player guessed A at first, but when asked to guess another letter (because they did not have enough money), they guessed C. When updating, the computer updated both for letter A and letter C, which I do not want.
Second, I am trying to have the player's balance update if they correctly guess a letter. For this, I have a separate function setup to update a balance based on the type of guess, but somewhere, the variable becomes undefined. This is the related code that I have for that part:
I am using parameters to do this, what is going wrong?
function spinWheel() {
spinAmount();
ask();
}
function spinAmount() {
var luck = randomNum(0, rewards.length);
var multiplier = rewards[luck];
if (multiplier == undefined) {
spinAmount();
} else {
alert("You spun $" + multiplier);
return multiplier;
}
updateBalance(multiplier);
}
function ask() {
console.log("Prompting");
var guess = prompt("What letter would you like to guess?");
var playerGuess = guess.toUpperCase();
console.log(playerName1 + " guessed " + playerGuess);
checkGuessType(playerGuess);
}
function checkGuessType(checkMe) {
console.log("Checking type...");
if (checkMe.length > 1) {
console.log(playerName1 + " guessed a word.");
} else if (checkMe == "A" || checkMe == "E" || checkMe == "I" || checkMe == "O" || checkMe == "U" && balance1 < 100) {
console.log(playerName1 + " tried to guess a vowel.");
alert("You cannot spin the wheel and guess a vowel!")
alert("You do not have enough money to buy a vowel. Guess a different letter.");
ask();
} else if (checkMe == "A" || checkMe == "E" || checkMe == "I" || checkMe == "O" || checkMe == "U" && balance1 > 100) {
console.log(playerName1 + " guessed a vowel.");
alert("You cannot spin the wheel and guess a vowel!")
alert("Since you guessed a vowel, you do not get any money added to your account. Instead, $100 was deducted.");
isVowel = true;
} else if (checkMe !== "") {
console.log(playerName1 + " guessed a consonant.");
} else if (checkMe == "") {
console.log(playerName1 + " did not guess.");
alert("Please guess a letter or word.")
ask();
}
checkForGuess(checkMe);
}
function checkForGuess(amIThere) {
console.log("Checking if letter is present...");
for (x = 0; x < magicyMagic.length; x++) {
if (amIThere == magicyMagic.charAt(x)) {
console.log("Ding ding ding!");
lettersMatched = lettersMatched + 1;
isCorrect = true;
output[x] = amIThere;
if (isVowel == false) {
updateBalance();
} else if (isVowel == true && nowGoing == 1) {
balance1 = balance1 - 100;
} else if (isVowel == true && nowGoing == 2) {
balance2 = balance2 - 100;
}
lettersMatched = 0;
document.getElementById("mysteryWord").innerHTML = output.join("");
document.getElementById("pl1Messages").innerHTML = "Player 1 - " + playerName1 + " has $" + balance1;
}
}
if (isCorrect == false && amIThere !== "") {
console.log("Player did not guess correctly...");
document.getElementById("mysteryWord").innerHTML = output.join("");
document.getElementById("pl1Messages").innerHTML = "There are no " + amIThere + "'s in the word.";
lettersMatched = 0;
document.getElementById("lastMessage").innerHTML = "Player 2 (" + playerName2 + ") will now go.";
}
hasBeenGuessed.push(amIThere);
console.log(hasBeenGuessed[0] + " has been added to the list. Players cannot guess this letter again.");
}
function updateBalance(totalMoneySpun) {
alert(totalMoneySpun)
if (nowGoing == 1) {
balance1 = balance1 + (lettersMatched * totalMoneySpun);
document.getElementById("pl1Messages").innerHTML = "Player 1 - " + playerName1 + " has $" + balance1;
}
}

Javascript adding to array using readline

I'm trying to repeatedly get 2 inputs and store them into an array until the word 'end' is typed. However, I'm getting undefined at the console.log(studentList[i]);
EDIT: With the help of you guys, I was able to store the values into the array. Right now what I want to do is to give a 'grade' to each of the marks that was entered. However no matter what number i entered, i was getting 'HD' for all the grades.
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function printList(list) {
for (let i = 0; i < studentList.length; i += 1) {
var grade;
if ((marks <= 100) && (marks => 80)){
grade = 'HD'
studentList[i][2] = grade;
}
else if ((marks <= 79) && (marks => 70))
{
grade = 'D'
studentList[i][2] = grade;
}
else if ((marks <= 69) && (marks =>60))
{
grade = 'C'
studentList[i][2] = grade;
}
else if ((marks <= 59) && (marks =>51))
{
grade = 'P'
studentList[i][2] = grade;
}
else if ((marks < 50) && (marks =>0))
{
grade = 'N'
studentList[i][2] = grade;
}
console.log(studentList[i]);
}
}
function Input()
{
while(true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') {
printList(studentList)
break
}
console.log("Student Name is" , name);
marks = readline.question("Enter marks for " + name + ": ");
if (marks === 'end') {
printList(studentList)
break
}
console.log("Marks for " + name + " is " + marks );
studentList.push([name, marks]);
}
}
Any advice would be much appreciated! Thanks!
You mainly need to change .Length to .length and you have to use a while loop combined with a break (once 'end' is typed) that comes out of the while loop to give you the list you want to print. By changing the location of the if statements you are able to adjust when the break can occur and when it reads from users input.
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function printList(list) {
for (let i = 0; i < list.length; i += 1) {
console.log('list[i]', list[i]);
}
}
function Input()
{
while(true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') {
printList(studentList)
break
}
console.log("Student Name is" , name);
marks = readline.question("Enter marks for " + name + ": ");
if (marks === 'end') {
printList(studentList)
break
}
console.log("Marks for " + name + " is " + marks );
studentList.push([name, marks]);
}
}
I don't think you know how many students there are ahead of time, so you will need to loop until "end" is detected.
This might help:
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function Input() {
while (true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') break;
console.log("Student Name is", name);
marks = readline.question("Enter marks for " + name + ": ");
console.log("Marks for " + name + " is " + marks);
studentList.push([name, marks]);
}
}
for (var i = 0; i <= studentList.Length; i++) {
console.log(studentList[i]);
}

JS while loop doesnt stop at true

When you run this script it shows the HP for both of the pokemon when you press 1 and click enter it subtracts your attack hit points to the enemies hit points. When you or the ememy hits 0 or less than 0 hit points it is supposed to stop and just show who won in the console log. Instead it takes an extra hit to for it to show the message.
So if you are at -10 hp it takes one more hit.
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
if (!firstFight) {
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
}
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
}
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
Are there any ways I can make this code more efficient?
you can simply add another if condition to check whether life of the player is still greater then '0' or less then '0' in the same turn like this.
in this way you don't have to go for next turn to check for the players life plus it rids off the extra conditional statements...
if (fightOptions == 1) {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
}
if (!firstFight){
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
}
}
}
The problem is, the points are getting subtracted after you check if they are equal to or below zero. Here is a way you can check before:
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
wildPokemon[0].hp -= pokeBox[0].attack.hp;
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
console.log(wildPokemon[0].hp);
}
pokeBox[0].hp -= wildPokemon[0].attack.hp;
if (!firstFight && pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
console.log(pokeBox[0].hp);
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
While loops stops when the condition is false, in you case, you set it to not false, it is not stopping because you did not explicitly determine it. There are 2 ways you can do.
1st:
while(!firstFight == false)
2nd:
var firstFight = true;
while(firstFight)
then set the firstFight to false inside your if else statements.

My javascript loop breaks before it gets through all if else statements

I'm trying to write a pin number guessing game and wrote out a bunch of if else statements but it stops working after I input the first pin (correct or incorrect), can anyone tell me what's going on?
var ans = prompt("Do you want to play?");
if (ans == "y") {
document.getElementById("ans").innerHTML = "You answered yes.";
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h1;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h2;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h3;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = "You lost. :(";
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("ans").innerHTML = "You answered no.";}
Here is the rest of the javascript but I don't think the problem lies there.
var nums = [0, 0, 0, 0];
for (var idx = 0; idx < nums.length; ++idx)
{
nums[idx] = Math.floor((Math.random() * 9) + 1);
}
pswd = nums.join("")
document.getElementById("nums").innerHTML = pswd;
function guessNum() {
var gNum = prompt("What do you think the number is?")
}
if (nums[3] % 2 == 0) {
var divis = "even";
} else {
var divis = "odd";
}
var h1 = "The first number is " + nums[0]
var h2 = "The sum of the middle numbers are " + (nums[1] + nums[2])
var h3 = "The last number is " + divis
The problem is that the variable gNum that you're creating inside the guessNum function only lives there. Javascript is function scoped.
When you get to the line if (gNum != pswd) {... gNum simply doesn't exist. Make guessNum return the value, and create the actual gNum variable on the same scope as the if.
function guessNum() {
return prompt("What do you think the number is?")
}
...
var gNum = guessNum();
if (gNum != pswd) {
...
I would also advise you to study while loops, to avoid these nested ifs. Keep the hard work! :)

How do I end javascript program mid program

I need some help ending my program. Is there a command to end it halfway through? In this short guess the number game i made everything goes fine unless the first person wins because it has to complete the loop even after the game has ended
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
Use break; to break the while loop like this:
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
break; // it will break the while loop
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
break; // it will break the while loop
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
Or you can define the process as a function when someone win the game return a value and it will end :
function game() {
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 100;
var theNumber = Math.round(timesNumber);
var playerOne = prompt("Player 1 please enter your name...");
var playerTwo = prompt("Player 2 please enter your name...");
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
return ; // it will end the function
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
return ; // it will end the function
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
}
game();
I think you are looking for continue
while (userInput != theNumber) {
var userInput = prompt(playerOne + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerOne + " has won!");
continue;
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
var userInput = prompt(playerTwo + ", Take a Guess (0-100)");
if (userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct. " + playerTwo + " has won!");
} else if (userInput < theNumber) {
alert("Higher");
} else {
alert("Lower");
}
}
The break statement, which was briefly introduced with the switch
statement, is used to exit a loop early, breaking out of the enclosing
curly braces.
To handle all such situations, JavaScript provides break and continue
statements. These statements are used to immediately come out of any
loop or to start the next iteration of any loop respectively.
Example
<script type="text/javascript">
<!--
var x = 1;
document.write("Entering the loop<br /> ");
while (x < 20)
{
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
document.write( x + "<br />");
}
document.write("Exiting the loop!<br /> ");
//-->
</script>
Information courtesy of TutorialsPoint.com
By changing a bit your logic:
Store Player names into an Array, change turn using 0,1,0,1... numbers,
Use only one prompt!! The current player is defined by players[turnNumber]
var rnd = Math.round( Math.random() * 5), // 0 - 5
res = -1, // Result
pl = [], // ["Ethan", "Roko"]
t = 0; // turn: 0,1,0,1... (0 = 1st player)
for(var i=0; i<2; i++) pl[i] = prompt("Player"+ (i+1) +", please enter your name:");
while (res !== rnd) {
res = parseInt( prompt( pl[t] + ", take a Guess (0-5)"), 10);
alert( res===rnd ? (res +" is correct! "+ pl[t] +" has won!") : (res<rnd? "Higher" : "Lower"));
t = ++t % 2; // increment turn and reset to 0 if === 2 Results in: 1,0,1,0...
}

Categories

Resources