How do i use a switch satement to check if the number divided by a number in an array == to 0.
how ive done it befor this is by using if statements and if else stateents to check:
if (i % num[0] == 0) {output thingy}
if (i % num[1] == 0) {output thingy}
and have an array named num.
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FizzBuzz</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<button onclick="plus()">+</button>
<button onclick="minus()">-</button>
<button onclick="zero()">0</button>
<h1>Number:</h1>
<h2 id="number">0</h2>
<h1>Value:</h1>
<h2 id="val">0</h2>
<script>
var output = "";
var val = document.getElementById("val");
var number = document.getElementById("number");
var i = 0;
function zero() {
i = 0;
number.innerHTML = (i);
output = "0";
val.innerHTML = (output);
}
function plus() {
i++;
thingy()
}
function minus() {
i--;
thingy()
}
function thingy() {
var num = [3, 5]; // The numbers to multiply
var out = ["Fizz", "Buzz"] // The outputs
number.innerHTML = (i);
output = "";
for (var i = 0; i < num.length; i++){
var number = num[i];
if (i % number == 0) {
switch (number[i]) {
case [0]:
output += out[0]
break;
case [1]:
output += out[1]
break;
}
if ( output == "" ) { output = i; }
val.innerHTML = (output);
}
}
</script>
</body>
</html>
You can use true as your switch condition.
Example:
switch (true) {
case (i % num[0] === 0) : output code; break;
case (i % num[1] === 0) : output code; break;
}
Also, it's worth noting that your structure here is possibly redundant:
if (i % number == 0) {
switch (i) {
case [0]: output += out[0]; break;
case [1]: output += out[1]; break;
}
}
It would be enough to have:
if (i % number == 0) {
output += out[i];
}
Related
I'm very new to coding and thus VS Code. I am on a mac. Whenever I try to link an external file in VS Code to another file it never works. I understand it has to be a bad file path but I cannot figure it out at all. I've tried removing files from folders so they're in their own section and this does not work.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Number Guessing Game</title>
</head>
<body>
<h1>Number Guessing Game</h1>
<button type="button" onclick="runGame()">Start Game</button>
<script src="/js/number-guessing-game.js"></script>
</body>
</html>
js file:
function runGame() {
let guessString = '';
let guessNumber = 0;
let correct = false;
let numtries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
// const target = Math.floor(Math.random() * 100) + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target);
} while (!correct);
alert('You got it! The number was' + target + '.\n\nIt took you' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target){
let correct = false;
if (isNaN(guessNumber)) {
alert('You have not entered a number.\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!');
} else if (guessNumber < target) {
alert('Your number is too small!');
} else {
correct = true;
}
} return correct;
}
Here's what file setup looks like:
You should pass the relative path instead of absolute:
<script src="js/number-guessing-game.js"></script>
Also you have syntax error in js, here is an working example:
function runGame() {
let guessString = '';
let guessNumber = 0;
let correct = false;
let numtries = 0;
const randomNumber = Math.random() * 100;
const randomInteger = Math.floor(randomNumber);
const target = randomInteger + 1;
// const target = Math.floor(Math.random() * 100) + 1;
do {
guessString = prompt('I am thinking of a number in the range 1 to 100.\n\nWhat is the number?');
guessNumber = +guessString;
numTries += 1;
correct = checkGuess(guessNumber, target);
} while (!correct);
alert('You got it! The number was' + target + '.\n\nIt took you' + numTries + ' tries to guess correctly.');
}
function checkGuess(guessNumber, target) {
let correct = false;
if (isNaN(guessNumber)) {
alert('You have not entered a number.\n\nPlease enter a number in the 1-100 range.');
} else if ((guessNumber < 1) || (guessNumber > 100)) {
alert('Please enter an integer in the 1-100 range.');
} else if (guessNumber > target) {
alert('Your number is too large!');
} else if (guessNumber < target) {
alert('Your number is too small!');
} else {
correct = true;
}
return correct;
}
I created a simple program that contains two buttons "higher" that adds 1 to the number and "lower" that subtracts 1 from the same number. When the number is negative it must change its color to red and when it is positive it must become green but that doesn't work.
Here's the javascript
let num = 0;
function higher() {
num ++;
document.getElementById("number").innerHTML = num;
}
function lower() {
num --;
document.getElementById("number").innerHTML = num;
}
// (conditionals statements below do not work for an unknown reason)
if (num < 0) {
document.getElementById("number").style.color = "red";
} else if (num > 0) {
document.getElementById("number").style.color = "green";
}
Here's the Html body
<body>
<div class="counter">
<div id="number">0</div>
<button onmousedown="higher()" class="btn_high">Higher</button>
<button onclick="lower()" class="btn_low">Lower</button>
</div>
</body>
Here's an example of how the program should look
https://romeojeremiah.github.io/Counter-Project/
You have to put the conditional statement inside a function and then call that function on each button click like this
let num = 0;
function higher() {
num ++;
document.getElementById("number").innerHTML = num;
colorChange();
}
function lower() {
num --;
document.getElementById("number").innerHTML = num;
colorChange();
}
function colorChange(){
if (num < 0) {
document.getElementById("number").style.color = "red";
} else if (num > 0) {
document.getElementById("number").style.color = "green";
}
}
Nothing is calling the code at the end, so you'll never see those results. Try wrapping your conditional in a function, then calling that function at the end of higher() and lower(). For example:
let num = 0;
function higher() {
num++;
document.getElementById("number").innerHTML = num;
checkNumberAndApplyStyles();
}
function lower() {
num--;
document.getElementById("number").innerHTML = num;
checkNumberAndApplyStyles();
}
function checkNumberAndApplyStyles() {
if (num < 0) {
console.log('under')
document.getElementById("number").style.backgroundColor = "red";
} else if (num > 0) {
document.getElementById("number").style.color = "green";
}
There is 2 option here: Score and Wrong.
I want this :
If answer.value is empty > wrong+1
If not, score+1.
But its not working.
There is a question here ; 4*0 (answer is 0 right?)
I dont write anything on my answer input. So, > answer.value == null
But, result is score+1. This is not i want.
I guess, answer.value == 0 right here. How can i do what i want?
if (result == answer.value) {
score.innerHTML = Number(score.innerHTML) + 1;
} else if (result != answer.value || answer.value == null) {
wrong.innerHTML = Number(wrong.innerHTML) + 1;
}
Complete JavaScript codes and html codes
//idleri alma
var sayi1, sayi2, islem, cevap, btn, dogru, yanlis;
sayi1 = document.getElementById("sayi1");
sayi2 = document.getElementById("sayi2");
islem = document.getElementById("islem");
cevap = document.getElementById("cevap");
btn = document.getElementById("btn");
dogru = document.getElementById("true");
yanlis = document.getElementById("false");
//random sayı oluşturma
function rSayi(ust, alt) {
return Math.floor(Math.random() * (ust - alt)) + alt;
}
function soru() {
sayi1.innerHTML = rSayi(5, 0);
sayi2.innerHTML = rSayi(5, 0);
//islem değişkeni üzerinde değişiklikler
var islemler = ["+", "-", "/", "*"];
islem.innerHTML = islemler[rSayi(4, 0)];
//bölme geldiğinde tam bölünebilme özelliği
if (islem.innerHTML == "/") {
while (true) {
if (sayi1.innerHTML % sayi2.innerHTML == 0) {
break;
}
sayi2.innerHTML = rSayi(50, 0);
}
}
//islem kontrolü
var sonuc, s1, s2;
s1 = Number(sayi1.innerHTML) // sayıları
s2 = Number(sayi2.innerHTML) // number veri türüne geçiş yaptırıyoruz
switch (islem.innerHTML) {
case "+":
sonuc = s1 + s2;
break;
case "-":
sonuc = s1 - s2;
break;
case "*":
sonuc = s1 * s2;
break;
case "/":
sonuc = s1 / s2;
break;
default:
break;
}
//dogru yanlis puanlarını arttırmak
//HERE IS THE PROBLEM!!
btn.onclick = function() {
soru();
var p1, p2;
p1 = Number(dogru.innerHTML);
p2 = Number(yanlis.innerHTML);
if (sonuc == cevap.value) {
dogru.innerHTML = p1 + 1;
//dogru.innerHTML = Number(dogru.innerHTML)+1; !diğer yöntem
} else if (sonuc != cevap.value || cevap.value == null) {
yanlis.innerHTML = p2 + 1;
//yanlis.innerHTML = Number(yanlis.innerHTML)+1; !diğer yöntem
}
}
}
//events
window.onload = function() {
soru();
}
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id="main">
<div id="sayi1">0</div>
<div id="islem">+</div>
<div id="sayi2">0</div>
<div id="equal">=</div>
<div id="_cevap"><input id="cevap"></div>
<div id="_btn"><button id="btn">Cevapla</button></div>
<div id="clear"></div>
<div id="true">0</div>
<div id="false">0</div>
</div>
</body>
</html>
The problem with your code is Number('') is 0 and not null
Hence when the <input > does not have value, the answer is considered to be 0, which is correct for 4 * 0
Also, use === wherever possible to prevent automatic type conversion like this.
What you could do is short-circuit the logic,
if(cevap.value === '') // empty is always wrong
yanlis.innerHTML = p2 + 1;
else {
... continue your code here
}
updated Code
//idleri alma
var sayi1, sayi2, islem, cevap, btn, dogru, yanlis;
sayi1 = document.getElementById("sayi1");
sayi2 = document.getElementById("sayi2");
islem = document.getElementById("islem");
cevap = document.getElementById("cevap");
btn = document.getElementById("btn");
dogru = document.getElementById("true");
yanlis = document.getElementById("false");
//random sayı oluşturma
function rSayi(ust, alt) {
return Math.floor(Math.random() * (ust - alt)) + alt;
}
function soru() {
sayi1.innerHTML = rSayi(5, 0);
sayi2.innerHTML = rSayi(5, 0);
//islem değişkeni üzerinde değişiklikler
var islemler = ["+", "-", "/", "*"];
islem.innerHTML = islemler[rSayi(4, 0)];
//bölme geldiğinde tam bölünebilme özelliği
if (islem.innerHTML == "/") {
while (true) {
if (sayi1.innerHTML % sayi2.innerHTML == 0) {
break;
}
sayi2.innerHTML = rSayi(50, 0);
}
}
//islem kontrolü
var sonuc, s1, s2;
s1 = Number(sayi1.innerHTML) // sayıları
s2 = Number(sayi2.innerHTML) // number veri türüne geçiş yaptırıyoruz
switch (islem.innerHTML) {
case "+":
sonuc = s1 + s2;
break;
case "-":
sonuc = s1 - s2;
break;
case "*":
sonuc = s1 * s2;
break;
case "/":
sonuc = s1 / s2;
break;
default:
break;
}
//dogru yanlis puanlarını arttırmak
//HERE IS THE PROBLEM!!
btn.onclick = function() {
soru();
var p1, p2;
p1 = Number(dogru.innerHTML);
p2 = Number(yanlis.innerHTML);
if(cevap.value === '') {
yanlis.innerHTML = p2 + 1;
} else if (sonuc == cevap.value) {
dogru.innerHTML = p1 + 1;
//dogru.innerHTML = Number(dogru.innerHTML)+1; !diğer yöntem
} else if (sonuc != cevap.value) {
yanlis.innerHTML = p2 + 1;
//yanlis.innerHTML = Number(yanlis.innerHTML)+1; !diğer yöntem
}
}
}
//events
window.onload = function() {
soru();
}
<html>
<head>
<title>Calculator</title>
</head>
<body>
<div id="main">
<div id="sayi1">0</div>
<div id="islem">+</div>
<div id="sayi2">0</div>
<div id="equal">=</div>
<div id="_cevap"><input id="cevap"></div>
<div id="_btn"><button id="btn">Cevapla</button></div>
<div id="clear"></div>
<div id="true">0</div>
<div id="false">0</div>
</div>
</body>
</html>
I wrote this code to validate credit card digits, saved it as an html file. It's not working though.
<html>
<head>
<script>
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
</script>
</head>
<body>
<form>
<input type="text"
name="cc_number"
onblur="if(mod10_check(this.value)){$('#cc_error').hide(); } else { $('#cc_error').show(); }"
value="" />
<span id="cc_er`enter code here`ror" style="display:none;">The card number is invalid.</span>
</form>
</body>
</html>
Does not validate value entered in the textbox. When the textbox goes out of focus message is not shown.Not willing to use any third party plugin.What is wrong with this code?
Try re-writing your inline code as an event handler.
var ccInp = document.getElementById('cc_no');
ccInp.addEventListener('blur', function() {
if(!mod10_check(ccInp.value)) {
document.getElementById('cc_error').style.display = '';
}
});
function mod10_check(val){
var nondigits = new RegExp(/[^0-9]+/g);
var number = val.replace(nondigits,'');
var pos, digit, i, sub_total, sum = 0;
var strlen = number.length;
if(strlen < 13){ return false; }
for(i=0;i
<strlen;i++){
pos = strlen - i;
digit = parseInt(number.substring(pos - 1, pos));
if(i % 2 == 1){
sub_total = digit * 2;
if(sub_total > 9){
sub_total = 1 + (sub_total - 10);
}
} else {
sub_total = digit;
}
sum += sub_total;
}
if(sum > 0 && sum % 10 == 0){
return true;
}
return false;
}
<form>
<input type="text"
name="cc_number"
value=""
id="cc_no"/>
<span id="cc_error" style="display:none;">The card number is invalid.</span>
</form>
jsFiddle: http://jsfiddle.net/8kyhtny2/
I've written a javascript function with some variables, i've tried to test it to see if variables would show in my HTML document but they wont and i have no idea why. Specifically, i'm trying to insert variable currentScore which is set to 0 at the beginning, so it should show 0 in a textbox, but it doesnt appear there.
Here is my javascript :
var who = 0;
var decision = 0;
var diceOne = 0;
var diceTwo = 0;
var currentScore = 0;
player playerAI = new player;
player playerOne = new player;
document.getElementById('currentScore').value = currentScore;
function rollDice() {
diceOne = Math.round(6 * Math.Random() + 1);
diceTwo = Math.round(6 * Math.Random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
while (playerAI.playing == true && playerOne.playing == true) {
makeMove();
}
}
function makeMove() {
if (who == 0) {
aiStrat();
game();
}
else {
game();
}
}
function game() {
if (decision == 1) {
rollDice();
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
decision = 0;
makeMove();
}
if (diceOne == 1 || diceTwo == 1){
currentScore = 0;
decision = 0;
who = 1 - who;
makeMove();
}
if (diceOne == 1 && diceTwo == 1) {
currentScore = 0;
if (who == 0) {
playerAI.totalScore = 0;
}
else {
playerOne.totalScore = 0;
}
decision = 0;
who = 1 - who;
makeMove();
}
}
if(decision == -1) {
if (who == 0){
playerAI.totalScore += currentScore;
playerAI.checkScore();
}
else {
playerOne.totalScore += currentScore;
playerOne.checkScore();
}
currentScore = 0;
decision = 0;
who = 1 - who;
}
}
function aiStrat() {
if (playerAI.totalScore < 60) {
if (currentScore < 30) {
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 60 && playerAI.totalScore < 80) {
if (currentScore < 20){
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 80){
if (currentScore < 10) {
decision = 1;
}
else {
decision = -1;
}
}
}
var player {
var totalScore = 0;
var playing = true;
function checkScore() {
if (totalScore >= 100) {
playing = false;
}
};
};
And my HTML document is this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="BigPig.css">
<script type="text/javascript" src="VorgurakendusedKD1\Vorgurakendused.js" ></script>
</head>
<body onload="javascript:mainFunction()">
<div class="centered" type="text/javascript">
<h1>BIG PIG</h1>
<button><input type="button" value="START FROM BEGINNING" onclick="mainFunction();">
<span></span></button>
<br>
<button><span>GREEN BUTTON</span></button>
<br>
<button><span>RED BUTTON</span></button>
<br>
<output class="textbox" type="text/javascript" id="currentScore">CURRENTSCORE:
</output>
<br>
<output class="textbox" type="text">CPU SCORE: </output>
<br>
<output class="textbox" type="text">PLAYER SCORE: </output>
<br>
<p>Player versus computer</p>
<br>
<p id="currentScore"></p>
</div>
</body>
</html>
Here: document.getElementById('currentScore').value = currentScore;you try to find an element before it has loaded, and that's why you can't assign a value to it.
Try putting document.getElementById('currentScore').value = currentScore; inside your onload-function, mainFunction()