Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I am trying to make a calculator with javascript. My code below takes the button clicks and adds them all together as a string. When the user presses the sum or equals button, the function is supposed to evaluate the string as an equation and log a result. for example result == "2 * 10" should return 20. My problem is that instead of doing that it just adds it together rather than multiplying or doing any other function like - or divide.
here is my code:
var result = 0;
function calc(digit){
if (digit == "sum"){
console.log(eval(result)) ;
}
else if (digit == "-"){
result + "-";
}
else if (digit == "+"){
result + "+";
}
else if (digit == "*"){
result + "*";
}
else if (digit == "/"){
result + "/";
}
else if (digit == "."){
result + ".";
}
else if (digit == "clear"){
location.reload();
}
else{
result += parseFloat(digit);
}
}
and here is an example of a button click for each function:
<button class="large" type="button" value="divide"onclick=calc("/")>/</button>
You need to use assignment operators for this.
For example, instead of result + "-", use result += "-". You had the right idea in your else block.
Anyways, since your code has multiple if/else conditionals, it would be better to use a switch statement
function calc(digit){
switch(digit) {
case: "sum":
console.log(eval(result));
break;
case "-":
result += "-";
break;
case "+":
result += "+";
break;
case: "*":
result += "*";
break;
case: "/":
result += "/";
break;
case: ".":
result += ".";
break;
case "clear":
location.reload();
break;
default:
result += parseFloat(digit);
}
}
Here's some more information on String Concatenation in JavaScript
http://www.w3schools.com/jsref/jsref_concat_string.asp
In your if stack, result + "-" doesn't do anything. To add the minus sign to the end of result, you would do something such as
result = result + "-";
or
result += "-";
Currently, result + "-" has the system do the concatenation of result and the string, but immediately loses it because you didn't store it back in result.
Related
// It is simple code
var num = prompt("put number");
// This way is not worked
switch (num) {
case num > 0:
console.log("num++");
break;
case num < 0:
console.log(num-2);
break;
}
// But this worked
if (num > 0){
console.log(num++);
} else if (num < 0){
console.log(num -2);
}
My first way by "switch" is not worked but "if" method worked.
I tried all of thing for changing code or other ways but the same result.
Please guys help me.
Because the statement num > 0 inside you case will return true or false.
If you do this:
switch (true) {
case num > 0:
console.log("num++");
break;
case num < 0:
console.log(num-2);
break;
}
It will work.
Cases cannot be expressions, you must normalize your input first.
Although it is valid to place an expression in a case, in this scenario a more tried-and-true way of dealing with this is to first normalize your input first.
You can determine direction for example:
var num = parseInt(prompt("put number"), 10);
var direction = num < 0 ? -1 : 1;
switch (direction) {
case 1:
console.log("num++");
break;
case -1:
console.log(num - 2);
break;
}
The switch acts as a case switcher, meaning you cannot make comparisons to create cases, just list cases by case, and perform some function from this case. The if / else structure is suitable for making comparisons, as the expected result in the if call is always a boolean.
Example:
const a = 1;
if (a === 1) {
console.log('hello');
} else {
console.log('sad');
switch (a) {
case 1 : console.log('hello'); break;
default: console.log('sad'); break;
In your case, I recommend using if/else if/else, as it is more recommended.
This question already has answers here:
Expression inside switch case statement
(8 answers)
Closed 8 years ago.
The evaluations in the console print in the second line seem correct, but the switch statement won't work. And I am not getting any errors.
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0:
console.log(i, " by three");
break;
case i % 5 === 0:
console.log(i, " by five ");
break;
}
}
http://jsfiddle.net/vL4omdxs/
As the comment said, that's not how you use switch/case.
You evaluate the condition in switch, then create different behaviours using cases.
Here is your code slightly modified (actually not so slightly, there's a small math twist):
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
//console.log(i % 3 === 0, i % 5 === 0);
switch (i % 15) {
case 0:
r.innerHTML += i + " by three and five<br>";
break;
case 3:
case 6:
case 9:
case 12:
r.innerHTML += i + " by three<br>";
break;
case 5:
case 10:
r.innerHTML += i + " by five<br>";
break;
}
}
<div id="r"></div>
Just a hint (offtopic, but might help): switch/case is not the best approach for the 3/5 problem. See how much simpler it looks using ifs:
var res = document.getElementById('r');
for (var i = 0; i < 100; i++) {
res.innerHTML += "<br>" + i + ": ";
if (i % 3 == 0) {
res.innerHTML += "by three ";
}
if (i % 5 == 0) {
res.innerHTML += "by five ";
}
}
<div id="r"></div>
Case expressions are tested for strict equality so you need to change the switch from switch (1) to switch (true). However note that only one of the case blocks will be executed.
That's not the way to do the switch statement. It must be:
switch (i % 3) {
case 0:
...
break;
case 1:
...
break;
}
The expression within switch brackets is compared with the expression after case keyword. Take your code as example:
for (var i = 0; i < 100; i++) {
console.log(i % 3 === 0, i % 5 === 0);
switch (i) {
case i % 3 === 0: // if (i) equals (i % 3 === 0), run this branch
console.log(i, " by three");
break;
case i % 5 === 0: // if (i) equals (i % 5 === 0), run this branch
console.log(i, " by five ");
break;
}
}
And please remember, "equal" here means ===. Since your case expressions all return boolean, they'll never be equal to your i, which is a number.
This question already has answers here:
JavaScript: Need functions to convert a string containing binary to hex, then convert back to binary
(4 answers)
Closed 9 years ago.
What is the easiest way to do this in Javascript? Currently my code is a giant switch block, is there an easier way?
Current code:
function convertBintoHex(input){
input = ""+input;
while(input.length < 8){
input = "0" + input;
}
input = [input.substring(0,4),input.substring(4,8)];
var output = "";
for(var i in input){
switch(input[i]){
case "0000":
output += 0;
break;
case "0001":
output += 1;
break;
case "0010":
output += 2;
break;
case "0011":
output += 3;
break;
case "0100":
output += 4;
break;
case "0101":
output += 5;
break;
case "0110":
output += 6;
break;
case "0111":
output += 7;
break;
case "1000":
output += 8;
break;
case "1001":
output += 9;
break;
case "1010":
output += 'A';
break;
case "1011":
output += 'B';
break;
case "1100":
output += 'C';
break;
case '1101':
output += 'D';
break;
case '1110':
output += 'E';
break;
case '1111':
output += 'F';
break;
}
}
while(output.charAt(0) == 0 && output.length > 1){
output = output.substring(1);
}
return "0x" + output;
}
Using built-in functions:
parseInt('1010101010', 2).toString(16)
This question already has answers here:
What is the difference between the `=` and `==` operators and what is `===`? (Single, double, and triple equals)
(5 answers)
Closed 1 year ago.
Pretty straight-forward what I want to do:
If the input is 0, it means that they didn't input a number and it
should tell you so.
When the input is 7, it should say that you got it right.
Anything else, it should tell you that you got it wrong.
But it just outputs the "7 is correct" line no matter what the input is, and I can't figure it out what is wrong.
<script type="text/javascript">
function problem2 ()
{
var number = 0;
var text=document.getElementById("output");
number = prompt("Enter a number between 1 and 10 please" , 0);
if (number = 0)
{
text.value = "You didn't enter a number!";
}
if (number = 7)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
}
</script>
<input type="button" value="Click here" onclick="problem2()">
<input id="output" type="text">
You're assigning with =. Use == or ===.
if( 0 == number ){
text.value = "You didn't enter a number!";
}
Also, be wary of your brace placement. Javascript likes to automatically add semicolons to the end of lines. Source.
You are using assignment operators as your conditionals instead of comparison operators:
if (number = 0) // falsy. Same as if (false)
{
text.value = "You didn't enter a number!";
}
if (number = 7) // truthy. Same as if (true)
{
text.value = "7 is correct!";
}
else
{
text.value = "Sorry, ", input, "is not correct!";
}
Alternatively you can use a switch and organize the conditionals a bit easier:
switch (number) {
case 0:
text.value = "You didn't enter a number!";
break;
case 7:
text.value = "7 is correct!";
break;
default:
text.value = "Sorry, ", input, "is not correct!";
break;
}
Here is a code with the some fixes and improvements (I commented what I changed):
function problem2 (){
//I multiplied by * 1 to work with numbers, also used || to default to 0 in case of NaN
var num = (prompt("Enter a number between 1 and 10 please" , 0) * 1) || 0;
var msg = "";
if (!num){ //I prefer this over 'num == 0'
msg = "You didn't enter a number!";
//you should use 'else if' in this case
}else if (num == 7){//'=' is for assignment, use '==' or '===' instead
msg = "7 is correct!";
}else{
//you had an undefined var 'input', you probably meant 'num'
//you also were connecting var and strings using commas, use '+' instead
msg = "Sorry, " + num + " is not correct!"; //added a space in ' is'
}
//no need to store the element in a var anymore :D
document.getElementById("output").value = msg;
}
Aditionally, two more changes can be made:
only one var (e.g var something = "", somethingElse = 99;)
assign the default text from the beginning, like var msg = "default" and remove the else
Note: an undocumented change I made was to rename some vars, I encourage everyone to stop using vars like number, text, string, if you have this bad habit, you will eventually use illegal var names by mistake.
I found this example to make range work with switch statement:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26) && (value <= 50)):
result = ">= 26.";
break;
case ((value >= 1) && (value <= 25)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
But if I modify the code and remove the second check for the value the example will still work:
function GetText(value)
{
var result;
switch (true)
{
case ((value >= 26)):
result = ">= 26 .";
break;
case ((value >= 1)):
result = "Between 1 and 25.";
break;
case (value == 0):
result = "Equals Zero.";
break;
}
return result;
}
So if I passed 29 even that I have two true cases the first one will be selected. My question is that how switch statement works in most of programming languages it will start comparing from the top or its only in this case (and is it good or bad to write it like that?).
switch statement checks for matches from top to bottom.
From MDN docs on switch statement:
If a match is found, the program executes the associated statements. If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.
I would do something like this (with if and else if chains):
function GetText(value) {
var result;
if (value == 0) {
result = "Equals Zero.";
} else if (value <= 25) {
result = "Between 1 and 25.";
} else if (value <= 50) {
result = "Between 26 and 50.";
}
return result;
}