Run multiple else if statements - javascript

When I run this code, only the INVALID (over 100) and High Distinction works. Any number below 80 also shows High Distinction. What have I done wrong?
function calculateGrade() {
var fvalue = Number(prompt('Please enter final score for unit. Enter a whole number only'));
document.write('The final score entered is ' + fvalue + '<br />');
if (fvalue > 100) {
document.write('INVALID');
} else if (80 <= fvalue <= 100) {
document.write('High Distinction');
} else if (70 <= fvalue <= 79) {
document.write('Distinction');
} else if (60 <= fvalue <= 69) {
document.write('Credit');
} else if (50 <= fvalue <= 59) {
document.write('Pass');
} else if (0 <= fvalue <= 49) {
document.write('Fail');
} else if (fvalue < 0) {
document.write('INVALID');
}
}
calculateGrade()

Your comparison syntax is invalid. You need to check one boundary at a time:
if (80 <= fvalue && fvalue <= 100) {
Same for the others.
To take it a step further, you only need to check one boundary, because the higher end is excluded by the else:
if (fvalue > 100) {
document.write('INVALID');
} else if (80 <= fvalue) {
document.write('High Distinction');
} else if (70 <= fvalue) {
// ...

This isn't java.
But you can surely try this.
else if ( (fvalue >= 80) && (fvalue<= 100)) {
document.write('High Distinction');

Related

Grade Conversion in HTML

So, I have been working on this code for class, and everything I have done never seems to work! My work is in Visual Code Studio, and it does not bring up any sort of errors. I've looked it up and everything, and I just can't figure out why I can't get an output!
It is a grade conversion. By reading my code I guess you can figure out the parameters of the conversion. I just can't seem to figure out what is going on!
<!DOCTYPE HTML>
<html>
<pre>
<body>
<script>
var grade=95;
if ((grade >= 90) (and) (grade <= 100)) {
document.write("A+ -- Exceptional!");
} else if ((grade >= 80) (and) (grade <= 89)) {
document.write("A -- Excellent!");
} else if ((grade >= 70) (and) (grade <= 79)) {
document.write("B -- Good!");
} else if ((grade >= 60) (and) (grade <= 69)) {
document.write("C -- Satisfactory");
} else if ((grade >= 50) (and) (grade <= 59)) {
document.write("D -- Barely Acceptable");
} else if ((grade >= 0) (and) (grade <= 49)) {
document.write("F -- Failure");
} else {
document.write("An accepted grade was not implemented into the system.");
}
</script>
</body>
</pre>
</html>
and is not a javascript operator.
Replace every (and) with &&
var grade = 95;
if (grade >= 90 && grade <= 100) {
document.write("A+ -- Exceptional!");
} else if (grade >= 80 && grade <= 89) {
document.write("A -- Excellent!");
} else if (grade >= 70 && grade <= 79) {
document.write("B -- Good!");
} else if (grade >= 60 && grade <= 69) {
document.write("C -- Satisfactory");
} else if (grade >= 50 && grade <= 59) {
document.write("D -- Barely Acceptable");
} else if (grade >= 0 && grade <= 49) {
document.write("F -- Failure");
} else {
document.write("An accepted grade was not implemented into the system.");
}
Also you should not have <pre> tags outside of the <body>

If Else Statement Disaster [duplicate]

This question already has answers here:
How does (A == B == C) comparison work in JavaScript?
(6 answers)
Closed 6 years ago.
today I decided I wanted to make a simple js code that would accept a number (in meters), and decide what the appropriate metric unit to use would be. The code turned out to be a little more complicated than I had expected, but I was able to figure out most of the bugs as I found them (even if it meant rearranging all of my code). However, when it came to my if/else statement I could not figure it out. If I put in a number that is less than 1 nothing happens. If I put in a number more than 9 it logs the same thing every time. The structure itself may need some work, but if someone could help me with the if/else statement I would be very thankful. Here is the code (init is called when the body loads):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
if (0.1 >= x >= 0.99) {
console.log("deci");
}
else if (0.100 >= x >= 0.999) {
console.log("centi");
}
else if (0.1000 >= x) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x <= 99) {
console.log("deca");
}
else if (100 <= x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Use && as AND operator in javascript
Convert these 100 <= x <= 999 to 100 <= x && x <= 999
You could simplify the check a bit and return if a condition is true.
function convertDown(x) {
if (x < 0.01) {
console.log("milli");
return;
}
if (x < 0.1) {
console.log("centi");
return;
}
if (x < 1) {
console.log("deci");
return;
}
console.log("error");
}
Your code has 2 sort of errors. One was simple to fix, that you have to add && between two conditions in if statement.
Now coming to the other part, the less than 1 items. It needed a different logic. Well, your maths seems to be needing bit attention. 0.1 is same as 0.100 and is same as 0.1000
I have updated the code to look for the number of digits after the decimal point and then console.log accordingly.
The updated code will be:
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convertDown(x) {
// checks the number of digits after decimal point
decimals = (x.split('.')[1] || []).length
if (decimals == 1 || decimals == 2) {
console.log("deci");
}
else if (decimals == 3) {
console.log("centi");
}
else if (decimals == 4) {
console.log("milli");
}
else {
console.log("error");
}
}
function convertUp(x) {
if (1 <= x && x <= 99) {
console.log("deca");
}
else if (100 <= x && x <= 999) {
console.log("hecto");
}
else if (1000 <= x) {
console.log("kilo");
}
else {
console.log("error");
}
}
function convertMetricMeters(x) {
if (x < 1) {
convertDown(x);
}
else if (x > 9) {
convertUp(x);
}
else {
console.log("Appropriate Metric Unit");
}
}
}
Working jsfiddle example: https://jsfiddle.net/w7pf3moL/
A simplified version with only 1 method convert(float x):
function init() {
var x = prompt("How many meters?");
convertMetricMeters(x);
function convert(x) {
if (x < 0.01) console.log("milli");
else if (x < 0.1) console.log("centi");
else if (x < 1) console.log("deci");
else if (x < 10) console.log("meter");
else if (x < 100) console.log("deca");
else if (x < 1000) console.log("hecto");
else console.log("kilo");
}
function convertMetricMeters(x) {
if (x > 0) {
convert(x);
} else {
console.log("Appropriate Metric Unit");
}
}
}
init();

My if statement "between" is giving me wrong result

I am new here. I have a problem with my if/else if statement.
I got this:
if (unalumno.notas >= "90" && unalumno.notas <= "100") {
unalumno.notas = "A";
} else if (unalumno.notas >= "80" && unalumno.notas <= "89") {
unalumno.notas = "B";
} else if (unalumno.notas >= "70" && unalumno.notas <= "79") {
unalumno.notas = "C";
} else if (unalumno.notas >= "60" && unalumno.notas <= "69") {
unalumno.notas = "D";
} else if (unalumno.notas <= "59") {
unalumno.notas = "F";
}
All the else if statement is giving to me the right result in letters, but the first if continue giving the result in numbers. Hope can understand me. Sorry for english lol
Have a good day
As I said in my comment, parse the integer out and change all of your comparisons to numbers instead of strings:
var unalumnoNotas = parseInt(unalumno.notas, 10);
if (unalumnoNotas >= 90 && unalumnoNotas <= 100) {
notas = "A";
} else if (unalumnoNotas >= 80 && unalumnoNotas <= 89) {
notas = "B";
} else if (unalumnoNotas >= 70 && unalumnoNotas <= 79) {
notas = "C";
} else if (unalumnoNotas >= 60 && unalumnoNotas <= 69) {
notas = "D";
} else if (unalumnoNotas <= 59) {
notas = "F";
}
Also, if you throw an error or return early if the value is greater than 100, you can remove all of the extra && <= 89
if (unalumnoNotas > 100) {
throw new Error('Number too high');
}
if (unalumnoNotas >= 90) {
notas = "A";
} else if (unalumnoNotas >= 80) {
notas = "B";
} else if (unalumnoNotas >= 70) {
notas = "C";
} else if (unalumnoNotas >= 60) {
notas = "D";
} else if (unalumnoNotas <= 59) {
notas = "F";
}
You should use integers for comparison, or just parseInt("your string").
You are comparing strings instead of the integers that you should be comparing. Instead of the numerical comparison you think you're doing, its actually comparing the position of the characters in the string on their ASCII position.
You should parse the value into an int type then compare to numbers instead of strings.

Different formulas in jQuery based on number entered [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I would like to use different formulas based on a number entered. For example, if a number is greater than 25,000,000, one computation will be performed. If a number less than 25,000,000 but greater than 10,000,000, another computation will be performed, etc.
Any suggestions on how to make the following work:
HTML:
<input type="text" id="calculation" name="submitted[calculation]" maxlength="20" class="form-text required">
jQuery:
$("#calculation").change(function () {
if (parseFloat(this.value) >= 25000000) {
alert("court determines rate");
if (parseFloat(this.value)( < 25000000 && >= 10000000)) {
alert(113000 + (((this.value) - 10000000) * 0.005));
if (parseFloat(this.value)( >= 1000000 && < 10000000)) alert(23000 + (((this.value) - 1000000) * 0.01));
if (parseFloat(this.value)( >= 200000 && < 1000000)) alert(7000 + (((this.value) - 200000) * 0.02));
if (parseFloat(this.value)( >= 100000 && < 200000)) alert(4000 + (((this.value) - 100000) * 0.03));
else {
alert((this.value) * .04)
}
})
});
UPDATE: I've updated the code (again) as follows, but am still not having any luck. Any constructive suggestions?
$("#calculation").change(function () {
var entry = parseFloat(this.value);
if (entry >= 25000000) {
alert("court determines rate");
}
else if (entry >= 10000000)) {
alert(113000 + (((this.value) - 10000000) * 0.005));
}
else (entry >= 1000000) {
alert(23000 + (((this.value) - 1000000) * 0.01));
}
else (entry >= 200000) {
alert(7000 + (((this.value) - 200000) * 0.02));
}
else (entry >= 100000) {
alert(4000 + (((this.value) - 100000) * 0.03));
}
else {
alert((this.value) * .04);
}
})
})
The syntax you used above is very hard to read and is invalid. You should only use parseFloat once and not use it everywhere. Here is a very simple example of what you should be doing:
$("#calculation").change(function () {
var parsedFloat = parseFloat(this.value);
if (parsedFloat > 25000000){
console.log('use formula 1. Number is greater than 25000000');
}
else if (parsedFloat > 10000000){
console.log('use formula2. Number is greater than 10000000 and less than or equal to 25000000');
}
else {
console.log('use formula3. Number is less than or equal to 10000000');
}
});
After some more trial and error, I figured out the problem. There was an extra end parenthesis within the first elseif.
Here is the corrected code:
$(document).ready(function () {
$("#calculation").change(function () {
var entry = parseFloat(this.value);
if (entry >= 25000000) {
alert("court determines rate");
} else if (entry >= 10000000) {
alert(113000 + (((this.value) - 10000000) * 0.005));
} else if(entry >= 1000000) {
alert(23000 + (((this.value) - 1000000) * 0.01));
} else if (entry >= 200000) {
alert(7000 + (((this.value) - 200000) * 0.02));
} else if (entry >= 100000) {
alert(4000 + (((this.value) - 100000) * 0.03));
} else {
alert((this.value) * .04);
}
});
});

Which style of code is better: being efficient or separating concerns?

I wonder if this might come down to personal taste or if there is a generally agreed upon answer to this. I've got a piece of code that could be written in one of two ways and though I think it's something of a trivial example in terms of efficiency, I'd like to know what the generally accepted answer is for future extrapolations.
Here's the code I currently have, essentially a score is passed and some text is updated accordingly. The colour of the text is also changed by the score value.
function getBSTotalText(score) {
var scoreText;
if (score >= 0 && score <= 12) {
scoreText = "0 - 12 HIGH RISK";
}
else if (score >= 13 && score <= 14) {
scoreText = "13 - 14 MODERATE RISK";
}
else if (score >= 15 && score <= 16) {
scoreText = "15 - 16 LOW RISK";
}
else if (score >= 16) {
scoreText = "16+ NO RISK";
}
else {
scoreText = "";
}
return scoreText;
}
function getBSTotalColour(score) {
var colour;
if (score >= 0 && score <= 12) {
colour = "red";
}
else if (score >= 13 && score <= 14) {
colour = "amber";
}
else if (score >= 15 && score <= 16) {
colour = "yellow";
}
else if (score >= 16) {
colour = "grey";
}
else {
colour = "white";
}
return colour;
}
Now I could easily refactor this into one function and just get it to return an array or object to save basically copying and pasting the same code into a distinct function which from my understanding would conform to DRY but then break SOLID. Would best practice be to keep these functions distinct or merge them into one?
In this example, I'd say there's a compelling reason to refactor to a single function as both functions are concerned with the same thing - getting some formatted text.
function getBSTotalDisplayInfo(score) {
var result = {};
if (score >= 0 && score <= 12) {
result.colour = "red";
result.scoreText = "0 - 12 HIGH RISK";
}
else if (score >= 13 && score <= 14) {
result.colour = "amber";
result.scoreText = "13 - 14 MODERATE RISK";
}
else if (score >= 15 && score <= 16) {
result.colour = "yellow";
result.scoreText = "15 - 16 LOW RISK";
}
else if (score >= 16) {
result.colour = "grey";
result.scoreText = "16+ NO RISK";
}
else {
result.colour = "white";
result.scoreText = "";
}
return result;
}
Check what part of the code is repeated and move that into an extra function. In your case it's actually quite easy:
function getBSTotal(score) {
// returns some kind of enum
if (score >= 0 && score <= 12)
return 0;
else if (score >= 13 && score <= 14)
return 1;
else if (score >= 15 && score <= 16)
return 2;
else if (score >= 16)
return 4;
else
return 5;
}
function getBSTotalText(score) {
// now map the enum either to a text
return ["0 - 12 HIGH RISK",
"13 - 14 MODERATE RISK",
"15 - 16 LOW RISK",
"16+ NO RISK"
][getBSTotal(score)] || "";
}
function getBSTotalColour(score) {
// … or map it to a color
return ["red",
"amber"
"yellow",
"grey",
"white"
][getBSTotal(score)];
}
You still can make it more efficient by evaluating getBSTotal(score) only once and passing that to the mapping functions instead of score.

Categories

Resources