error shows on using && operator in chrome snippets - javascript

prompt("Enter your name");
var lifeExpectancy = Math.random() ;
lifeExpectancy = Math.floor(lifeExpectancy * 100) + 30;
// if (lifeExpectancy > 100){alert(lifeExpectancy + " Years, as old as Dinosaurs")}
if (lifeExpectancy <= 100 && > 75 ){
alert(lifeExpectancy + " Years , Many more birthdays to come !!!")
} else{
alert(lifeExpectancy + " Years.")
}
Shows error on using && and <= operators

You need to mention the name of variable again for the second comaprison
prompt("Enter your name");
var lifeExpectancy = Math.random() ;
lifeExpectancy = Math.floor(lifeExpectancy * 100) + 30;
if (lifeExpectancy <= 100 && lifeExpectancy > 75 ){
alert(lifeExpectancy + " Years , Many more birthdays to come !!!")
} else{
alert(lifeExpectancy + " Years.")
}

Related

Javascript multiplication table specifics

I am trying to complete a multiplication table but am running into an issue, this is my code...
function multiTable(number) {
var table = '';
for (i = 1; i < 11; i++) {
if (i == 1 || number == 2 || number == 3 || number == 4 || number == 5 || number == 6 || number == 7 || number == 8 || number == 9) {
table += i + " * " + number + " = " + (i * number) + "\n";
} else if (i = 10) {
table += i + " * " + number + " = " + (i * number);
}
}
return table;
}
When I put it through the tests provided I get ...
'1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50\n'
I am supposed to get ...
'1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50'
To save anyone some time the only difference is the very end, the \n after 50.
I don't know if this will help but this is the test:
Test.describe("Basic tests",() => {
Test.assertEquals(multiTable(5), '1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50');
})
function multiTable(number) {
var table = '';
for(var i = 1; i < 10; i += 1){ // print 9 times with \n
table += i + " * " + number + " = " + (i * number) + "\n";
}
table += 10 + " * " + number + " = " + (10 * number); // and last line
return table;
}
console.log(multiTable(5));
.as-console-wrapper { max-height: 100% !important; top: 0; }
i figured out the solution here it is
function multiTable(number) {
var table = '';
for(i=1;i<11;i++){
if(i === 10){
table += i+ " * " +number+ " = " +(i*number);
}else{
table += i+ " * " +number+ " = " +(i*number)+ "\n";
}
}
return table;
}

Dice Game - need to roll more dice based upon circumstances

I am developing a game idea. Weapons can be equipped on your character. Different weapons have different amounts of damage dice and critical hit dice. I have it working currently so that the program rolls the appropriate amount of dice based on your equipped weapon.
However, the program only rolls one critical dice, despite whether the equipped weapon contains two critical roll dies.
var WepEquipped = { "name": "Broken Sword", "attack_dice": "2", "critical_dice": "1", "min_base_dmg": "2", "max_base_dmg": "12", "max_total_dmg": "24", "weapon_type": "Slash" };
function Attack(rolls) {
var total = 0;
var dice = [];
for (var i = 1; i <= rolls; i++) {
var d6 = Math.floor((Math.random() * 6) + 1);
$("#dice_container").append("<div class='die_roll'><p class='atk-roll'>" + d6 + "</p></div>");
dice.push(d6);
total += d6;
}
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
$('#attack_button').off('click').on('click', function(){
$('.die_roll').hide();
Attack(WepEquipped.attack_dice);
// Attack(WepEquipped.attack_dice);
});
I can explain much more, but I hope this is enough code to grasp what I'm asking. Something here needs to change but I cannot figure out what:
// Needs to be able to roll for multiple critical dice
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
your grep returns the number of elements in the dice array that equal to your first roll and if the length of that array equals the number of rolls that were made you roll the critical dice once.
if ($.grep(dice, function (elem) {
return elem === dice[0];
}).length == rolls) {
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
$("#attack").html("<div>You attack for " + total + "</div>");
};
If you're trying to roll as many times as the grep returns you need something like this.
var crits = $.grep(dice, function (elem) {return elem === dice[0];});
if( crits.length == rolls ){
for( var x=0;x<crits.length;x++){
var d12 = Math.floor((Math.random() * 12) + 1);
total += d12;
$("#dice_container").append("<div class='die_roll'><p id='crit-roll'>" + d12 + "</p></div>");
}
}
Sorry for the double post, was on an abandoned account.

Odd behavior with else if statement (javascript)

As far as I can tell the code works fine normally but when more information is added or edited then the if else statement starts behaving oddly. It's reading the percent value correctly but it's not returning the correct letter string.
var total = function (){
var earned = 0;
for(i = 0; i < Assignments.length; i++){
earned += parseInt(Assignments[i].earned);
}
var possible = 0;
for(i = 0; i < Assignments.length; i++){
possible += parseInt(Assignments[i].possible);
}
var percent = (Math.floor((earned/possible) * 100));
console.log(percent);
//grade letter
if (percent >= 90){
grade.innerHTML = '';
grade.innerHTML = 'A ' + percent + '%';
} else if (percent <= 89 && 80 >= percent){
grade.innerHTML = '';
grade.innerHTML = 'B ' + percent + '%';
} else if (percent <= 79 && 70 >= percent){
grade.innerHTML = '';
grade.innerHTML = 'C ' + percent + '%';
} else if (percent <= 69 && 60 >= percent){
grade.innerHTML = '';
grade.innerHTML = 'D ' + percent + '%';
} else if(percent <= 59 && 0 >= percent){
grade.innerHTML = '';
grade.innerHTML = 'F ' + percent + '%';
} else {grade.innerHTML = '';}
};
After a few inputs it will return something like this:
I think it might be the else if statements conflicting, but honestly I have no idea why this is behaving this way.
You have your comparisons backward in the else ifs, you're using 70 >= percent rather than percent >= 70 (and so on).
Separately, there's no reason to assign '' to innerHTML if you're about to assign something else to it, and there's no reason to reiterate the upper bound (percent <= 89 and such), because you're using else if, so the percent >= 90 branch will have already been followed. Reiterating them is also a maintenance problem (you'll change one but forget to change the other).
So:
if (percent >= 90) {
grade.innerHTML = 'A ' + percent + '%';
} else if (percent >= 80) {
grade.innerHTML = 'B ' + percent + '%';
} else if (percent >= 70) {
grade.innerHTML = 'C ' + percent + '%';
} else if (percent >= 60) {
grade.innerHTML = 'D ' + percent + '%';
} else if (percent >= 0) {
grade.innerHTML = 'F ' + percent + '%';
} else {
grade.innerHTML = '';
}
Or of course, you can use a map, since your grade boundaries are evenly divisible by 10:
// Somewhere central
var grades = {
6: 'D',
7: 'C',
8: 'B',
9: 'A',
10: 'A'
};
// ...then simply:
if (percent >= 0) {
grade.innerHTML = (grades[Math.floor(percent / 10)] || 'F') + ' ' + percent + '%';
} else {
grade.innerHTML = "Less than 0?!";
}
var grades = {
6: 'D',
7: 'C',
8: 'B',
9: 'A',
10: 'A'
};
function showGrade(percent) {
var grade;
if (percent >= 0) {
grade = (grades[Math.floor(percent / 10)] || 'F') + ' ' + percent + '%';
} else {
grade = "Less than 0?!";
}
snippet.log(grade);
}
var n;
for (n = 0; n <= 100; ++n) {
showGrade(n);
}
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
If-Else condition range looking wrong, try this code...
var total = function (){
var earned = 0, possible = 0;
for(i = 0; i < Assignments.length; i++){
possible += parseInt(Assignments[i].possible);
earned += parseInt(Assignments[i].earned);
}
var percent = (Math.floor((earned/possible) * 100));
console.log(percent);
//grade letter
if (percent >= 90){
grade.innerHTML = 'A ' + percent + '%';
} else if (percent >= 80 && percent <= 89){
grade.innerHTML = 'B ' + percent + '%';
} else if (percent >= 70 && percent <= 79){
grade.innerHTML = 'C ' + percent + '%';
} else if (percent >= 60 && percent <= 69){
grade.innerHTML = 'D ' + percent + '%';
} else if(percent >= 0 && percent <= 59){
grade.innerHTML = 'F ' + percent + '%';
} else {grade.innerHTML = '';}
};
Although i have optimized some code no need 2 loops there, you can sum earned, possible variable in single loop, and no need to .innerHTML = '' when you assigning value in element.
I found a nice post on efficiency using different methods of comparing things. I still suggest using a switch-block instead of if/else, but it's technically not better than your solution, but as I thinks it nicer to read. Here is a code snippet:
switch (true) {
case (0 <= val && val < 1000): /* do something */ break;
case (1000 <= val && val < 2000): /* do something */ break;
...
case (29000 <= val && val < 30000): /* do something */ break;
}
Taken from this post. There's also an interesting table (in the first answer)
Switch statement for greater-than/less-than
and different methods of making this work. I know this is actually not a solution for your answer, but it might come in handy if you need to add more if/else and are doing some huge lists with values.

I am having trouble with a few javascript do while loops

I am writing a code guessing program to test the security of some iPhone passwords (This is not in anyway connected to anything illegal or is used to break into actual iPhones). The do/while loops just end all response once they occur and the last two lines don't print to the console.
print("Hi!");
print("I am a password security tester.");
var tries = 0
var guess1 = 0
var guess2 = 0
var guess3 = 0
var guess4 = 0
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
var password1 = (Math.floor(Math.random()*9));
var password2 = (Math.floor(Math.random()*9));
var password3 = (Math.floor(Math.random()*9));
var password4 = (Math.floor(Math.random()*9));
var password = (password1 * 1000) + (password2 * 100) + (password3 * 10) + password4;
print("This is the randomly genorated password: " + password);
print("And now begins the guessing");
do{
guess1 + 1;
tries + 1;
}while (password1 != guess1);
do{
guess2 + 1;
tries + 1;
}while (password2 != guess2);
do{
guess3 + 1;
tries + 1;
}while (password3 != guess3);
do{
guess4 + 1;
tries + 1;
}while (password4 != guess4);
print("Complete in " + tries + " tries");
print("The answer is: " + guess);
Jacob Ewing's answer is correct, but another problem is that guess will still be 0 at the end, because it doesn't automatically update. You'll need to do:
var guess = (guess1 * 1000) + (guess2 * 100) + (guess3 * 10) + guess4;
Before:
print("Complete in " + tries + " tries");
print("The answer is: " + guess);
You need to be using a += operator instead of just +
Saying guess1 + 1 returns the value of guess1 + 1, but does not increment that value directly, so you get an infinite loop.

Find the sum of a Javascript array and divide by its length

I'm almost embarrassed to ask this.
I'm a beginner programmer, and Javascript is very confusing to me. I managed to put together this much with the help of my instructor, but there are some simple things I can't get right.
I tried search Stack Overflow for a thread that would answer my question, but all of them I've seen contain code that I haven't learned about yet, so they're all just gibberish to me.
What I'm trying to do is add all the values of an Array and divide the sum by the array's length, ergo, find the average. The description of the assignment is find the average of any number of students' grades.
My two problems are
I can't figure out how to get the sum of all numeric values in the Array and,
For some reason, array.length returns one more than the actual length of the Array, even if I add a -1. (ex. if I enter 6 values, the array.length would return 7.)
I know where the problem is but I can't figure out what I need to enter. This assignment is due tomorrow, so anyone's time and effort is appreciated.
Here is my script:
<script type="text/javascript">
var allGrades = new Array();
var g = 0;
var l = 0;
var s = 0;
var t = 0;
do {
allGrades[g] = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "")
g++;
}
while (allGrades[g - 1] != "x")
for (l = 0; l < allGrades.length - 1; l++) {
s += allGrades[l] // Where I think the problem is
}
t == s / g - 1;
g == allGrades.length - 1; //
window.alert(g)
switch (t) {
case (t >= 90):
window.alert("Your average grade is " + (t) + ". " + "This is an A.")
break;
case (t >= 80 && t < 90):
window.alert("Your average grade is " + (t) + ". " + "This is a B.")
break;
case (t >= 70 && t < 80):
window.alert("Your average grade is " + (t) + ". " + "This is a C.")
break;
case (t >= 60 && t < 70):
window.alert("Your average grade is " + (t) + ". " + "This is a D.")
break;
case (t <= 60):
window.alert("Your average grade is " + (t) + ". " + "This is a failing grade.")
break;
}
</script>
I'm sorry if what I'm asking seems dumb. I've only been taking web programming for about two months, so I could really use some help!
Kyle
== is the comparison operator. You need to use the assignment operator (=) here:
t==s/g-1;
And the lines near it.
Also, for your own sake, do not use single-letter variable names unless you have a good reason for doing so.
Here's a cleaner way of writing the script:
var grades = [];
do {
var input = window.prompt("Please enter one grade for each window. After you enter a grade, enter an 'x' to see the average of the grades you entered.", "");
grades.push(parseFloat(input));
} while (input != 'x');
var sum = 0;
for (int i = 0; i < grades.length; i++) {
sum += grades[l];
}
var average = (sum / grades.length) * 100;
var grade;
if (average >= 90) {
grade = 'A';
} else if (average >= 80) {
grade = 'B';
} else if (average >= 70) {
grade = 'C';
} else if (average >= 60) {
grade = 'D';
} else {
grade = 'failing grade';
}
alert('Your average grade is ' + average + '. ' + 'This is a ' + grade);
t==s/g-1;
g==allGrades.length-1; //
Are both Comparisons, for assignment they should be
t=s/g-1;
g=allGrades.length-1;

Categories

Resources