Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
Please help me, I am studying on my own and need help, I want to create an "JavaScript else if statement" but this doesn't work.
Who wants to make input
// If "x" is greater than or equal to 1 and "x" is less than 10, and "y" is equal to 100, output "+"
// If "x" is greater than or equal to 11 and "x" is less than 100, and "y" is equal to 100, output "++"
// If "x" is greater than or equal to 1 and "x" is less than 10, and "y" is equal to 1, output "+++"
// If "x" is greater than or equal to 10, and "y" is equal to 1, output "++++"
The code that I tried to make, below
<!DOCTYPE html>
<html>
<body>
<p>Please Help:</p>
<input id="numb1" type="text">
<input id="numb2" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="tes"></p>
<script>
function myFunction() {
var x, y, text;
x = document.getElementById("numb1").value;
y = document.getElementById("numb2").value;
if (x > 1 || x < 10 || y == 100) {
text = "+";
} else if (x > 11 || x < 100 || y == 100) {
text = "++";
} else if (x > 1 || x < 10 || y == 1) {
text = "+++";
} else if (x > 10 || y == 1) {
text = "++++";
}
document.getElementById("tes").innerHTML = text;
}
</script>
</body>
</html>
Full Working Code:
<!DOCTYPE html>
<html>
<body>
<p>Please Help:</p>
<input id="numb1" type="text">
<input id="numb2" type="text">
<button type="button" onclick="myFunction()">Submit</button>
<p id="tes"></p>
<script>
function myFunction() {
var x, y, text;
x = document.getElementById("numb1").value;
y = document.getElementById("numb2").value;
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
document.getElementById("tes").innerHTML = text;
}
</script>
</body>
</html>
Explanation:
You were using || which means or in logical statements, where you meant to use && to represent and.
Furthermore, when using logical statements, more than or equal to would be represented by >= and not >.
What you used:
if (x > 1 || x < 10 || y == 100) {
text = "+";
} else if (x > 11 || x < 100 || y == 100) {
text = "++";
} else if (x > 1 || x < 10 || y == 1) {
text = "+++";
} else if (x > 10 || y == 1) {
text = "++++";
}
What you were supposed to use:
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
To learn more about JavaScript Operators and Comparison Logical Operators (i.e. ||, &&, >, >=, == or !=), visit:
https://www.w3schools.com/js/js_comparisons.asp
https://www.w3schools.com/jsref/jsref_operators.asp
Recommended changes to code:
I would strongly recommend adding an else statement to the conditional statement in you code, as then if all other conditions don't apply there will be a back-up, and your code will not error out and print out undefined.
first: the OR - || opartor returns true even if only one of the expression in is both sides are true. the AND - && operator returns true only if both of them are true, and this is what you are looking for.
so you have to replece all the OR opartors with AND operators.
second: to check if a value is greater than or equal to another value, you have to combine both operators > and = together.
if (x >= 1 && x < 10 && y == 100) {
text = "+";
} else if (x >= 11 && x < 100 && y == 100) {
text = "++";
} else if (x >= 1 && x < 10 && y == 1) {
text = "+++";
} else if (x >= 10 && y == 1) {
text = "++++";
}
Related
I have a program that calculates students percentages in a class and need the final output to all be in one box. however my program currently does on alert box for each student how do I fix this?
here is the code
<script>
function studentName(x)
{
while(x == '' || x >= 0 || x < 0)
{
if(x == '')
{
x = prompt('Cannot leave field blank. Enter again');
}
else if (x >= 0)
{
x = prompt('Cannot Enter a number. Enter again')
}
else
{
x = prompt('Cannot Enter a number. Enter again')
}
}
return(x)
}
function studentScore(y)
{
while(y == '' || y > 100 || y < 0 || isNaN(y))
{
if (y == '')
{
y = parseFloat(prompt("Cannot leave field, blank please enter students score"));
}
else if (y > 100 || y < 0)
{
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
}
else
{
y = parseFloat(prompt("Invalid score, please enter a score 0-100"));
}
}
return(y)
}
function another(z)
{
while(z == '' && z != 'n' && z != 'N' && z != 'y' && z != 'Y')
{
while (z == '' && z != 'n' && z != 'N' && z != 'y' && z != 'Y' )
{
z = prompt('Invalid response, would you like to enter another score Y/N ')
}
while(z == 'n' || z == 'N')
{
Z = prompt('Would you like to enter another student')
}
while (z == 'y' || z == 'Y')
{
z = prompt("Enter another score")
}
}
return(z)
}
var names = []
var scores = []
var redo = true
var anotherName
var redo2
var retry = true
var anotherScore
var retry2
var i = 0
var a = 1
var score = 0
while(redo == true)
{
var studentNames = prompt('Enter student name');
var name = studentName(studentNames);
names.push(name)
while(retry == true)
{
var studentScores = parseFloat(prompt('Enter student score'));
score = score + studentScore(studentScores);
retry = prompt('Enter another score? Y/N');
retry = another(retry); /**/
if(retry == 'y' || retry == 'Y')
{
retry = true
a++
}
else if(retry == 'n' || retry == 'N')
{
retry = false
}
}
score = score / a
scores[i] = score
redo = prompt('Enter another student? Y/N');
redo = another(redo); /**/
if(redo == 'y' || redo == 'Y')
{
redo = true
retry = true
i++;
a = 1
score = 0
}
else if(redo == 'n' || redo == 'N')
{
redo = false
}
}
var message = ""
for(y=0; y < names.length; y++)
{
alert(names[y] + " - " + scores[y]);
}
again I have a program that calculates students percentages in a class and need the final output to all be in one box. however my program currently does on alert box for each student how do i fix this and get all of the students names into one final alert box?
You are getting separate alerts because you're calling alert on every iteration with individual values. One solution could be to combine the names and the corresponding scores in a new array and call alert once on this array. Using join('\n') on the new array will convert the array elements to string and separate each array elements with new line, for the sake of formatting. Just change the last part with:
let roster = [];
for(let y=0; y < names.length; y++) {
roster.push(names[y] + " - " + scores[y]);
}
alert(roster.join('\n'))
Better yet if you save names and scores in one array from the beginning, like the roster. In this way you could avoid additional iteration at the end.
I am building an application similar to minesweeper where a user will click a square on a grid and the app will tell the user how many of the surrounding squares contain an 'X'. I have my code working when I only check up, down, left, and right. My code is beginning to get very long since there are quite a few edge cases to account for. I am going to begin checking diagonals for 'X's and I want to come up with a shorter way to check these cases.
Can anyone help me develop a for loop or other short hand way to write this code. Here is what I have so far for a 8x8 grid.
Here is my sandbox: https://codesandbox.io/s/6y6wzo001w
showNumber= () => {
let Xcounter = 0;
console.log(this.props.keys)
console.log(this.props.reduxState.reducer.board[this.props.keys])
if(this.props.keys% 8 ===0){
if(this.props.reduxState.reducer.board[this.props.keys +1] === 'X'){
Xcounter++
}
}
if(this.props.keys% 8 ===7){
if(this.props.reduxState.reducer.board[this.props.keys -1] === 'X'){
Xcounter++
}
}
if(this.props.keys/8 <1){
if(this.props.reduxState.reducer.board[this.props.keys +8] === 'X'){
Xcounter++
}
}
if(this.props.keys/8 >=7){
if(this.props.reduxState.reducer.board[this.props.keys -8] === 'X'){
Xcounter++
}
}
if(this.props.keys % 8 !== 0 && this.props.keys % 8 !== 7){
if(this.props.reduxState.reducer.board[this.props.keys +1] === 'X'){
Xcounter++
}
if(this.props.reduxState.reducer.board[this.props.keys -1]=== 'X'){
Xcounter++
}
}
if(Math.floor(this.props.keys)/8 > 0 && Math.floor(this.props.keys)/ 8 < 7){
if(this.props.reduxState.reducer.board[this.props.keys +8] === 'X'){
Xcounter++
}
if(this.props.reduxState.reducer.board[this.props.keys -8]=== 'X'){
Xcounter++
}
}
if(this.props.id === 'X'){
this.setState({...this.state, clicked: true, counter: 'X'})
return this.state.counter;
}
this.setState({...this.state, clicked: true, counter: Xcounter})
return this.state.counter;
}
Assuming you have an array this.props.reduxState.reducer.boardof length 64 with 'X's or non-'X's, one could simply loop through the x and y directions like so:
let Xcounter = 0;
//save the board for shorter and more readable code
let board = this.props.reduxState.reducer.board;
//the current index we've clicked on
let c = this.props.keys;
//we're going to check if we're at the edge of the board.
//I'll explain these later.
let minX = c%8 == 0 ? 0 : -1;
let maxX = c%8 == 7 ? 0: 1;
let minY = (c-minX)/8 == 0 ? 0 : -1;
let maxY = (c-minY)/8 == 7 ? 0 : 1;
for( let x = minX; x <= maxX; ++x ){
for( let minY = -1; y <= maxY; ++y ){
if( board[c+x+8*y)] == 'X' ){ Xcounter++; }
}
}
//we also checked the square itself, but we didn't want to
if( board[c] == 'X' ){ Xcounter--; }
This assumes the indeces of the board are from right to left, and then top to bottom, not the other way around (i.e. board[7] is the top-right corner, not the bottom-left one).
As far as what this actually does; essentially, we look whether or not we're at the edge of a board, and find the relative x- and y-coordinates we have to check. To visualize:
Here minX=0, because going to the left of the current clicked square c would throw us off the board. maxX=1 though, because we can check to the right of the clicked square. Similarly, we check the y-coordinates.
Assuming that your checks are already correct, let's work with what you already have.
Try to rewrite what you actually have with more condensed style to get an overview as a first step and introduce a board side constant as a second:
showNumber = () => {
const BOARD_SIDE = 8;
let Xcounter = 0;
let keys = this.props.keys;
let board = this.props.reduxState.reducer.board;
console.log(keys);
console.log(board[this.props.keys]);
for (let edge = BOARD_SIDE; edge < BOARD_SIDE * BOARD_SIDE; edge += BOARD_SIDE) {
if (keys % edge === 0 && board[keys + 1] === "X") Xcounter++;
if (keys % edge === (edge - 1) && board[keys - 1] === "X") Xcounter++;
if (keys / edge < 1 && board[keys + edge] === "X") Xcounter++;
if (keys / edge >= (edge - 1) && board[keys - edge] === "X") Xcounter++;
if (keys % edge !== 0 && keys % edge !== (edge - 1)) {
if (board[keys + 1] === "X") Xcounter++;
if (board[keys - 1] === "X") Xcounter++;
}
if (Math.floor(keys) / edge > 0 && Math.floor(keys) / edge < (edge - 1)) {
if (board[keys + edge] === "X") Xcounter++;
if (board[keys - edge] === "X") Xcounter++;
}
}
if (this.props.id === "X") {
this.setState({ ...this.state, clicked: true, counter: "X" });
return this.state.counter;
}
this.setState({ ...this.state, clicked: true, counter: Xcounter });
return this.state.counter;
};
I'm looking at projecteuler.net's 4th problem, and have come across a curious feature that I'm wondering if anyone could explain.
The following code returns 10001
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
n;
}
}
n--;
}
whereas when wrapped in an IIFE, it returns 906609 which is the correct answer.
(function euler4() {
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
return n;
}
}
n--;
}
}());
Does anybody know why? I can't find an explanation online. Cheers!
The lone n in the first does not terminate the algorithm, whereas the return n in the second does. This can be fixed by replacing n in the first with a simple break
var n = 999 * 999; //biggest product with 3 digit numbers
var x;
while (n>10000) { //smallest product of 3 digit numbers
if (n.toString() === n.toString().split('').reverse().join('')) {
x = Math.floor(Math.sqrt(n));
while (n % x !== 0 && x >= 100 && n/x <= 999) {
x--;
}
if (n % x === 0 && x>= 100 && n/x <= 999) {
break;
}
}
n--;
}
console.log(n);
I have to write Java script that can read two integers from the user, if the first number the user entered is evenly divisible by the second number, then it will display an alert of TRUE to the user, and FALSE otherwise. If either number the user enters is ZERO the alert should display FALSE to the user.
this is my code it does not work
var y = prompt("Enter a Value","");
var z = prompt("Enter a Value","");
if (y % z === 0) {
greeting = "TRUE";
} else (y % z !== 0 ||
{
greeting = "FALSE"
document. get Element By Id ("true false").inner HTML = greeting;
If either number the user enters is ZERO the alert should display
FALSE to the user.
change you if condition to
if (x && y && y % z === 0) {
Rest of the code is
if (x && y && y % z === 0)
{
greeting = "TRUE";
}
else
{
greeting = "FALSE";
}
If you are new to javascript here is another way to implement this very common pattern using the ternary operator:
var greeting = (x && y && y % z === 0) ? "TRUE" : "FALSE";
I'm trying to check whether the variable y is less than x and greater than z, but this boolean expression is returning false for some reason. Does JavaScript allow boolean expressions to be written concisely like this? If so, what is the correct syntax?
x = 2;
y = 3;
z = 4;
if(x > y > z){
alert("x > y > z"); //Nothing happens!
}
Try using the logical and operator:
if (x > y && y > z) {
to guarantee both conditions are true.
DEMO: http://jsfiddle.net/3sxvy/
If you need to put this into a function, you could try:
function compareNumbers(direction) {
var inOrder = (function () {
if (direction === "desc") {
return function (current, before) {
return current <= before;
};
} else if (direction === "asc") {
return function (current, before) {
return current >= before;
};
}
})();
var valid = true;
for (var i = 2; i < arguments.length; i++) {
if (!inOrder(arguments[i], arguments[i-1])) {
valid = false;
break;
}
}
return valid;
}
if (compareNumbers("desc", 33, 5)) {
console.log("Good");
} else {
console.log("Bad");
}
DEMO: http://jsfiddle.net/kn6M4/1/
Change your test to
if (x > y && y > z){
When you write (x > y > z), this is equivalent to ((x>y)>z), so you're comparing a boolean (x>y) to z. In this test, true is converted to 1, which isn't greater than 2.
You want
if(x > y && y > z){
alert("x > y > z"); //Nothing happens!
}
Javascript will try to parse your original statement from left to right and you'll end up comparing z to a boolean value which will then be parsed to a number (0 or 1).
So your original statement is equivalent to
if( (x > y && 1 > z) || (x <= y && 0 > z))