I'm trying to code a program to receive a number and map it to a letter grade based mark using javascript, and html.
When I run the code, I don't get any answers.
Here is the code:
HTML
<h1>mapping a numerical grade to a letter grade</h1>
</header>
<div class="column1">
<div class="input">
a <input id="number1" type="number" min=" -32768" max=" 32767" />
</div>
<div class="input">
<button onclick="mapping()">enter</button>
</div>
<strong><p id="output"></p></strong>
</div>
Javascript
function mapping() {
var a = parseInt(document.getElementById("number1").value);
switch (true) {
case a > 89:
answer = "A+";
break;
case a > 79:
answer = "A";
break;
case a > 74:
answer = "B+";
break;
case a > 69:
answer = "B";
break;
case a > 64:
answer = "C+";
break;
case a > 59:
answer = "C";
case a > 54:
answer = "D+";
case a > 49:
answer = "D";
break;
case a > 40:
answer = "E";
break;
default:
answer = "F";
document.getElementById("output").innerHTML = answer;
}
document.getElementById("output").innerHTML = answer; is inside the switch statement. It will be executed with default only
This code will work:
function mapping() {
var a = parseInt(document.getElementById("number1").value);
switch (true) {
case a > 89:
answer = "A+";
break;
case a > 79:
answer = "A";
break;
case a > 74:
answer = "B+";
break;
case a > 69:
answer = "B";
break;
case a > 64:
answer = "C+";
break;
case a > 59:
answer = "C";
case a > 54:
answer = "D+";
case a > 49:
answer = "D";
break;
case a > 40:
answer = "E";
break;
default:
answer = "F";
}
document.getElementById("output").innerHTML = answer;
}
switch (true) doesn't work. switch (1) does.
Also, I think case only accepts values, not comparisons -- at least when I tried it with Chrome and Opera. So you might want to rewrite this using if-else statements.
Related
im new with JS and i read about the switch statement. i dont know how to use it
i got an exercise to complete.
got an array with numbers 1-10 and the result need to be with words like "one","two","three"..
Thats what i got so far :
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(numbers) {
case "1":
text = "one";
break;
case "2":
text = "two";
break;
case "3":
text = "three";
break;
case "4":
text='four';
break;
case "5":
text = "five";
break;
case "6":
text = "six";
break;
case "7":
text = "seven";
break;
case "8":
text = "eight";
break;
case "9":
text = "nine";
break;
case "10":
text = "ten";
}
}
return text;
}
sayNum()
You could do it like this, for example:
function sayNum(){
let numbers = [1,2,3,4,5,6,7,8,9,10];
let result = [];
for(let i=0;i<numbers.length;i++) {
switch(numbers[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text = "four";
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
break;
}
result.push(text);
}
return result;
}
let namedNumbers = sayNum();
console.info(namedNumbers);
This will:
Add the textual values to an array, representing each number in the source array
Return the resulting array to the caller
Log the result in the console
In the switch statement, you pass an 'expression' into the switch statement. The expression itself can be a string, a number, float, boolean etc. Now, the expression is compared to each of the case clause. And this is a 'strict' comparison. And that is the reason why your code was not working.
Firstly you were passing an undeclared variable, 'numbers' as the switch expression. Instead, you should be passing the ith element of the nameNumber[i] array like so: switch(nameNumber[i]){ }
And, secondly, in each of your case clauses, you are comparing the value to a string like "1", "2". But the switch expression is compared using strict equality === operator, therefore when your nameNumber array contains numbers and not strings, your 'case' clauses should also have numbers and not strings. That means case 1: instead of case "1":.
You can read more about the switch-case here: Switch Statement
I have fixed your code below with the changes I mentioned above. Please run the below code snippet to see how it works. Goodluck!
function sayNum(){
let nameNumber = [1,2,3,4,5,6,7,8,9,10]
let text = '';
for(let i=0;i<nameNumber.length;i++){
switch(nameNumber[i]) {
case 1:
text = "one";
break;
case 2:
text = "two";
break;
case 3:
text = "three";
break;
case 4:
text='four';
break;
case 5:
text = "five";
break;
case 6:
text = "six";
break;
case 7:
text = "seven";
break;
case 8:
text = "eight";
break;
case 9:
text = "nine";
break;
case 10:
text = "ten";
}
console.log(text);
}
return text;
}
sayNum();
Rather than using a switch, use if statement. Because in switch, break statement can be used to jump out of a loop.
let text = '';
function sayNum() {
let nameNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < nameNumber.length; i++) {
if(nameNumber[i] == 1){
text += `"one",`;
}
if(nameNumber[i] == 2){
text += `"two",`;
}
if(nameNumber[i] == 3){
text += `"three",`;
}
if(nameNumber[i] == 4){
text += `"four",`;
}
if(nameNumber[i] == 5){
text += `"five",`;
}
if(nameNumber[i] == 6){
text += `"six",`;
}
if(nameNumber[i] == 7){
text += `"seven",`;
}
if(nameNumber[i] == 8){
text += `"eight",`;
}
if(nameNumber[i] == 9){
text += `"nine",`;
}
if(nameNumber[i] == 10){
text += `"ten"`;
}
}
}
sayNum();
console.log(text)
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
var answer = "low";
case 4:
case 5:
case 6:
var answer = "medium";
break;
} else if(val => 7) {
var answer = "Huge"
}
return answer;
}
it says error Declaration or statement expected. ts(1128) [13, 7]
and it poits at the else if statement
You can use the "default" keyword, but you should probably update your code in order to handle the cases in which the value of the parameter is not positive or not a number:
function texas(val) {
if (val <= 0 || isNan(val)) {
throw new InvalidOperationException("val should be a positive number");
}
switch(val) {
case 1:
case 2:
case 3:
return "low";
case 4:
case 5:
case 6:
return "medium";
default:
return "Huge"
}
}
It's >= and the elsehas to be deleted. The varfor answer is unnecesary, just declare it once with let. You forgot the break in case 3:.
function texas(val) {
let answer = "";
switch(val) {
case 1:
case 2:
case 3:
answer = "low";
break;
case 4:
case 5:
case 6:
answer = "medium";
break;
}
if(val >= 7) {
answer = "Huge"
}
return answer;
}
console.log(texas(2));
console.log(texas(8));
You just need to return in the switch
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
var answer = "low";
return answer;
case 4:
case 5:
case 6:
var answer = "medium";
return answer;
}
if(val => 7) {
var answer = "Huge"
}
return answer;
}
The syntax does not allow to put an else after a switch. else only makes sense in combination with an if statemen. But switch has a default: case which most closely matches your intention (hopefully):
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
var answer = "low";
break;
case 4:
case 5:
case 6:
answer = "medium";
break;
default:
if(val >= 7) {
answer = "Huge"
}
// decide what should happen if val is 0, -1 or not even a number (e.g. texas('gotcha!')
break;
}
return answer;
}
Don't forget to put break in your cases, otherwise execution will "fall through" and execute the next cases. You would never end up with "low"
You can't use an if statement within a switch block.
You do have the default option tho -
function texas(val) {
var answer = "";
switch(val) {
case 1:
case 2:
case 3:
answer = "low";
case 4:
case 5:
case 6:
answer = "medium";
break;
default:
answer = val >= 7 ? "Huge" : "Invalid";
break;
}
return answer;
Note that if you have a minus / negative answer, it'll also fall into this clause, but you can the the value of answer with an inline ?: if statement...
You can't put the else after the switch block as people have stated above. switch statement is better for multi way branching and fixed data values. On the other side, if statement is better for boolean values. You can do something like this. It might not be the shortest line of codes, but just so you that there's another approach:
function texas(val) {
let answer = "";
switch (true) {
case (val == 1 || val == 2 || val == 3):
answer = "low";
break;
case (val == 4 || val == 5 || val == 6):
answer = "medium";
break;
case (val >= 7):
answer = "huge";
break;
}
return answer;
}
I'm trying to learn how to do a switch statement using javascript. Can you guys help me how to convert this one into switch statement?
if (x == ix && y == iy){//should be the default
x.style.backgroundColor = 'white';
}
if(x < ix){
x.style.backgroundColor = 'red';
}
else if(x > ix){
x.style.backgroundColor = 'blue';
}
if(y < iy){
x.style.backgroundColor = 'green';
}
else if(y > iy){
x.style.backgroundColor = 'yellow';
}
JavaScript does not support operations other than strict equality in switches. In other words, you cannot write that program as a switch.
In a switch, you can compare a variable to different values (or cases) and check if they are equal. If they are, you execute the code given under the case.
There is a drawback, however, and it is that you can convert this code into a switch easily:
if (a === 1) {
console.log("one");
} else if (a === 2) {
console.log("two");
} else {
console.log("Out of range! :(");
}
The above code in switch is
switch (a) {
case 1:
console.log("one");
break;
case 2:
console.log("two");
break;
default:
console.log("Out of range! :(");
break;
}
But you cannot do the same to a code that contains relational operations.
switch (a) {
case > 1: // throws error
doSomething();
break;
}
Hope this could be helpful to convert your above conditions.
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
I need to brush up on my javascript because it is my weakest language, so I thought "Hey lets make a simple 'translating' program to test my skills". Well I was able to make it translate one way so far(I havent worked on untranslating the stuff people input), but anyway the way it does it is by a series of many cases inside a switch. Im wondering if there is anyway I can simplify the code instead of having a million switch cases. Thanks here is my code.
function main() {
var get = prompt("Enter what you would like to encode!","At the current time decoding is still a WIP").toLowerCase();
var ina = [...get];
for(i = 0; i < ina.length; i++) {
switch(ina[i]) {
case "a":
ina[i] = "z";
break;
case "b":
ina[i] = "y";
break;
case "c":
ina[i] = "x";
break;
case "d":
ina[i] = "w";
break;
case "e":
ina[i] = "v";
break;
case "f":
ina[i] = "u";
break;
case "g":
ina[i] = "t";
break;
case "h":
ina[i] = "s";
break;
case "i":
ina[i] = "r";
break;
case "j":
ina[i] = "q";
break;
case "k":
ina[i] = "p";
break;
case "l":
ina[i] = "o";
break;
case "m":
ina[i] = "n";
break;
case "n":
ina[i] = "m";
break;
case "o":
ina[i] = "l";
break;
case "p":
ina[i] = "k";
break;
case "q":
ina[i] = "j";
break;
case "r":
ina[i] = "i";
break;
case "s":
ina[i] = "h";
break;
case "t":
ina[i] = "g";
break;
case "u":
ina[i] = "f";
break;
case "v":
ina[i] = "e";
break;
case "w":
ina[i] = "d";
break;
case "x":
ina[i] = "c";
break;
case "y":
ina[i] = "b";
break;
case "z":
ina[i] = "a";
break;
default:
ina[i] = ina[i]
};
};
var outa = ina.join("");
document.getElementById("output").innerHTML = outa;
};
You could use an object with properties like
{
a: 'z',
b: 'y',
c: 'x',
// ...
z: 'a'
}
Usage with the default value of ina[i].
ina[i] = object[ina[i]] || ina[i];
You could use a couple string variables to map the letters.
function translateLetter(input) {
const untranslated = "abcdefghijklmnopqrstuvwxyz";
const translated = "zyxwvutsrqponmlkjihgfedcba";
var i = untranslated.indexOf(input);
return translated[i];
}
The switch you're using has logic that can be implemented directly without needing the switch at all via simple math (I believe most modern JS interpreters should JIT away the actual method calls if this is a hot loop, so the cost there should be trivial):
var get = prompt("Enter what you would like to encode!","At the current time decoding is still a WIP").toLowerCase();
var ina = [...get];
for(i = 0; i < get.length; i++) {
var code = get.charCodeAt(i);
if (97 <= code && code <= 122) { // 'a' and 'z' ordinal values
// Invert lowercase letters with simple math and convert back to character
ina[i] = String.fromCharCode((122 + 97) - code);
}
// No need to handle non-lowercase/non-ASCII since ina initialized to match get
}
Just do the math on the ASCII character codes:
function main() {
var get = prompt("Enter what you would like to encode!","At the current time decoding is still a WIP").toLowerCase();
var ina = [...get];
for (i = 0; i < get.length; i++) {
var charNum = get.charCodeAt(i) - 96;
if (charNum > 0 && charNum < 27) {
ina[i] = String.fromCharCode((27 - charNum) + 96);
}
};
var outa = ina.join("");
document.getElementById("output").innerHTML = outa;
};
I'm learning JavaScript. Very new and know basic. I'm playing with various options of JavaScript.
I'm comparing a-z (lower case) and A-Z (upper case) from user input. and giving an answer base on the input.
Normally i can do this with this long code:
var x = prompt("Enter Your character");
switch (x) {
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
case 'g':
case 'h':
case 'i':
case 'j':
case 'k':
case 'l':
case 'm':
case 'n':
case 'o':
case 'p':
case 'q':
case 'r':
case 's':
case 't':
case 'u':
case 'v':
case 'w':
case 'x':
case 'y':
case 'z':
document.write("Lower case");
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
case 'G':
case 'H':
case 'I':
case 'J':
case 'K':
case 'L':
case 'M':
case 'N':
case 'O':
case 'P':
case 'Q':
case 'R':
case 'T':
case 'U':
case 'V':
case 'W':
case 'X':
case 'Y':
case 'Z':
document.write("Upper case");
break;
default:
document.write("It is number");
break;
}
With switch I want to achieve same output but with less code! Something like this:
var x = prompt("Enter Your character");
switch(x) {
case x >= 'a'|| x <= 'z':
document.write("Lower case");
break;
case x >= 'A' || x <= 'Z':
document.write("Upper case");
break;
default:
document.write("It is number");
break;
}
Any Help?
Please I want to do this with only switch function. I know i can do this with if/else function but i want to do this with switch. If its not possible with switch let me know :-)
The switch statement compares the input expression with each case statement using strict comparison.
So use true inside the switch clause and specify expressions that evaluate to true in case clause:
var x = prompt("Enter Your character");
switch (true) {
case x >= "a" && x <= "z":
alert("Lower case");
break;
case x >= "A" && x <= "Z":
alert("Upper case");
break;
default:
alert("Something else");
break;
}
I personally do not recommend this. This is only for learning.
You can try it with something like this.
<script>
var x=prompt("Enter Your character");
if (x.test(/[a-z]/)) {
document.write("Lower case");
} else if (x.test(/[A-Z]/)) {
document.write("Upper case");
} else {
document.write("It is number");
}
</script>
You can see more info here: https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
You could do a simple if/else
var x=prompt("Enter Your character");
if(!isNaN(x))
console.log("It is number");
else if(x.toLowerCase()==x)
console.log("Lower case");
else if(x.toUpperCase()==x)
console.log("Upper case"););
Check if the character is in in between other characters:
var x=prompt("Enter Your character");
if (x >= '0' && x <= '9')
alert("number!");
else if(x >= 'a' && x <= 'z')
alert("lowercase!");
else if(x >= 'A' && x <= 'Z')
alert("uppercase!");
else
alert("not a letter!");
The parameter to a case statement is something to perform an equality comparison with, you don't put a comparison there. If you want to do a comparison, use if, not switch. Also, you should be combining the comparisons with &&, not ||
if (x >= 'a' && x <= 'z') {
document.write('Lower case');
} else if (x >= 'A' && x <= 'Z') {
document.write('Upper case');
} else if (x >= '0' && x <= '9') {
documennt.write('Number');
} else {
document.write('Something else');
}
Try also:
var x = prompt("Enter Your character");
var find = x.match(/([a-z]*)([A-Z]*)([0-9]*)/);
var type = ["Lower case","Upper case", "It is number"];
document.write(find ? type[find.lastIndexOf(x)-1] : "Unknown char")