simple calculator returning alert statments but ignoring actual functions - javascript

hey everyone im in my first semester and im pretty new to javascript. i have an assignment thats due in in a few hours and i have been racking my brain trying to figure out why my code wont display the actual function results. this is the assignment.
**Write JavaScript program which implements a fully functioning, five feature
(addition, subtraction, multiplication, division, and modulo/remainder) calculator.
when i run my code it acts like i dont have any input values and returns my alert statement with a 0 or a NaN.
MY CODE SO FAR
var input1 = 0;
var input2 = 0;
var again = true;
function main()
{
while (again === true)
{
inputnum1();
inputnum2();
operator();
}
}
function inputnum1()
{
var input1 = 0;
input1 = parseInt(prompt("Input first number: ", "1"));
while ((isNaN(input1)) || (input1 < 1))
{
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function inputnum2()
{
var input2 = 0;
input2 = parseInt(prompt("Input second number: ", "1"));
while ((isNaN(input2)) || (input2 < 1))
{
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
input2 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function operator()
{
var option = 0;
var string = "";
string += "\nEnter 0 to terminate calculator: ";
string += "\nEnter 1 for addition: ";
string += "\nEnter 2 for subtraction : ";
string += "\nEnter 3 for multiplication: ";
string += "\nEnter 4 for division: ";
string += "\nEnter 5 for modulo/remainder: ";
option = parseInt(prompt(string, "1"));
while ((isNaN(option)) || (option < 0) || (option >5))
{
option = parseInt(prompt(string, "1"));
}
chosenop(option);
}
function chosenop(option)
{
switch (option)
{
case 0:
alert ("Terminated successfully");
again = false;
break;
case 1:
addition();
break;
case 2:
subtract();
break;
case 3:
multiply();
break;
case 4:
divide();
break;
case 5:
modulo();
break;
}
}
function addition()
{
var sum = input1+input2;
alert ("The sum is: " + sum);
}
function subtract()
{
var diff = input1-input2;
alert("The difference is: " + diff);
}
function multiply()
{
var prod = input1*input2;
alert ("The product is: " + prod);
}
function divide()
{
var quot = (input1 + 0.0)/(input2 + 0.0);
alert ("The quotient is: " + quot);
}
function modulo()
{
var mod = input1%input2;
alert ("The modulo is: " + mod);
}
main();

First off, I'd like you to read through this guide.
Now, to your assignment. This line in inputnum2():
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
is superflous.
At the beginning of your code, you have defined variables input1 and input2. However, in inputnum1() and inputnum2() you do var input1 = 0 and var input2 = 0, which limits their scope to the function block. Here's a wikipedia article on scope. So essentially, just remove them.
This is what your code should look like:
var input1 = 0;
var input2 = 0;
var again = true;
function main()
{
while (again === true)
{
inputnum1();
inputnum2();
operator();
}
}
function inputnum1()
{
input1 = parseInt(prompt("Input first number: ", "1"));
while ((isNaN(input1)) || (input1 < 1))
{
input1 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function inputnum2()
{
input2 = parseInt(prompt("Input second number: ", "1"));
while ((isNaN(input2)) || (input2 < 1))
{
input2 = parseInt(prompt("Numeric values starting at 1 only: " , "1"));
}
}
function operator()
{
var option = 0;
var string = "";
string += "\nEnter 0 to terminate calculator: ";
string += "\nEnter 1 for addition: ";
string += "\nEnter 2 for subtraction : ";
string += "\nEnter 3 for multiplication: ";
string += "\nEnter 4 for division: ";
string += "\nEnter 5 for modulo/remainder: ";
option = parseInt(prompt(string, "1"));
while ((isNaN(option)) || (option < 0) || (option >5))
{
option = parseInt(prompt(string, "1"));
}
chosenop(option);
}
function chosenop(option)
{
switch (option)
{
case 0:
alert ("Terminated successfully");
again = false;
break;
case 1:
addition();
break;
case 2:
subtract();
break;
case 3:
multiply();
break;
case 4:
divide();
break;
case 5:
modulo();
break;
}
}
function addition()
{
var sum = input1+input2;
alert ("The sum is: " + sum);
}
function subtract()
{
var diff = input1-input2;
alert("The difference is: " + diff);
}
function multiply()
{
var prod = input1*input2;
alert ("The product is: " + prod);
}
function divide()
{
var quot = (input1 + 0.0)/(input2 + 0.0);
alert ("The quotient is: " + quot);
}
function modulo()
{
var mod = input1%input2;
alert ("The modulo is: " + mod);
}
main();

Related

Simple card game

I've created a simple higher or lower card guessing game, it works but once it completes once it then loops through the game logic n^2 times and I cant explain why. I'm really new to coding and JavaScript and I cant figure out what's happening. The issue I currently have is while I'm able to look up concepts in isolation I don't understand enough about the bigger picture to know what interaction is causing the looping.
less useful further info:
Currently the whole script is really a proof of concept, ultimately I will replace the deck building function and just use the random number generator to find images of cards, record all of the previous game events and remove cards from the deck as the game progresses but I cant have it looping by the square of the number of times its been through the game cycle.
Here is the code, please feel free to talk to me like I'm 5, I currently feel like a monkey with a gun.
console.log(">>>>>>>>>>>>>>>>>>>>>>> SCRIPT START");
console.log("variables are defined");
var suitClubs = [];
var suitDiamonds = [];
var suitHearts = [];
var suitSpade = [];
var history = [];
var userGuess;
var activeCard;
var nextCard;
var randomSuitOne;
var randomCardOne;
var randomSuitTwo;
var randomCardTwo;
var activeCardValue;
var nextCardValue;
var gameCycle = 0;
const card = document.querySelector(".card");
const title = document.querySelector(".title");
const historyP = document.querySelector(".history-p");
console.log("buildDeck() is called")
buildDeck();
function buildDeck() {
console.log("Deck is built");
for (i = 1; i <= 13; i++) {
suitDiamonds.push(i + " Diamond");
}
for (i = 1; i <= 13; i++) {
suitHearts.push(i + " Heart");
}
for (i = 1; i <= 13; i++) {
suitClubs.push(i + " Club");
}
for (i = 1; i <= 13; i++) {
suitSpade.push(i + " Spade");
}
var deck = suitClubs.concat(suitDiamonds, suitHearts, suitSpade);
console.log("cardChoice is called");
cardChoice();
};
function cardChoice() {
gameCycle = gameCycle + 1;
console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE START");
title.innerHTML = "Higher or Lower!"
activeSequenceCard();
// console.log("activeSequenceCard is called to randomize the active card");
function activeSequenceCard() {
randomSuitOne = Math.floor((Math.random() * 4) + 1);
randomCardOne = Math.floor((Math.random() * 13));
switch (randomSuitOne) {
case 1:
activeCard = suitClubs[randomCardOne];
break;
case 2:
activeCard = suitDiamonds[randomCardOne];
break;
case 3:
activeCard = suitSpade[randomCardOne];
break;
case 4:
activeCard = suitHearts[randomCardOne];
break;
}
card.innerHTML = activeCard;
nextSequenceCard();
// console.group("nextSequenceCard is called to randomize the next card in the deck")
}
function nextSequenceCard() {
randomSuitTwo = Math.floor((Math.random() * 4) + 1);
randomCardTwo = Math.floor((Math.random() * 13));
switch (randomSuitTwo) {
case 1:
nextCard = suitClubs[randomCardTwo];
break;
case 2:
nextCard = suitDiamonds[randomCardTwo];
break;
case 3:
nextCard = suitSpade[randomCardTwo];
break;
case 4:
nextCard = suitHearts[randomCardTwo];
break;
}
historyP.innerHTML = ("The next card will be: " + nextCard);
console.log("randomSuitOne is: " + randomSuitOne + " randomCardOne is: " + randomCardOne);
console.log("randomSuitTwo is: " + randomSuitTwo + " randomCardTwo is: " + randomCardTwo);
gamePlay();
}
}
function gamePlay() {
for (let i = 0; i < 2; i++) {
document.getElementsByClassName("game-button")[i].addEventListener("click", function () {
userGuess = parseInt(this.value);
console.log("The users guess was button (" + this.value + ") " + this.innerHTML + " and is a: " + typeof this.value);
switch (userGuess) {
case 1: console.log("User clicked HIGHER");
if (activeCardValue <= nextCardValue) {
console.log("Case 1: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 1: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
case 2: console.log("User clicked LOWER");
if (activeCardValue >= nextCardValue) {
console.log("Case 2: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 2: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
} console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE ENDS, this is cycle: " + gameCycle);
})
}
activeCardValue = activeCard.split(" ");
activeCardValue = parseInt(activeCardValue.splice(0, 1));
console.log("activeCardValue is: " + activeCardValue);
nextCardValue = nextCard.split(" ");
nextCardValue = parseInt(nextCardValue.splice(0, 1));
console.log("nextCardValue is: " + nextCardValue);
}

A Game of Hand Cricket - Javascript

I am trying to make a simple game, in the below function handCricketBat(), the if conditional statement is getting skipped even when the condition batsMan = bowlerMan is satisfied. It always moves on to the else statement. Can someone tell me why this is happening.
function handCricketBat(){
var total = 0;
for (x = 1; x <=6; x++){
var batsMan = prompt("Ball " + x + " \nEnter Between 1-6");
var bowlerMan = randomBall();
console.log("The bowler - "+ bowlerMan);
if (batsMan === bowlerMan) {
console.log("Howzattt");
break;
}
else if (batsMan !== bowlerMan) {
console.log("That's good batiing, scoring a " + batsMan);
continue;
}
total += +batsMan;
}
console.log(total);
}
function randomBall(){
return Math.floor(Math.random()*7);
}
Your batsMan is a string.
Use var batsMan = parseInt(prompt("Ball " + x + " \nEnter Between 1-6")); instead and it should work.

Javascript Loop - can't figure this one out

I've tried everything that crossed my mind, but no luck with this loop (although i'm pretty new to javascript).
Prompt should ask a question until nothing entered. At that point all the 'results' that were previously entered should be taken and processed.
Result should look like (if entered for 1st prompt: 'CS A 4', 2nd 'BB B 3', 3rd 'CC C 3'..):....showing only after there was not entry for nth prompt
COURSE GRADE HOURS
CS A 4
BB B 3
CC C 3
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>gpa.html</title>
</head>
<script type="text/javascript">
function getData(){
var input=0,
results=[];
while(input!==""){input = prompt("Enter course name, grade and credit hours (e.g., 'CS3520 A 4' or click OK with no data to terminate.");
input = input.split(" ");
if(input==""){
results.push({
course: input[0].trim(),
grade: input[1].trim(),
creditHours: parseInt(input[2], 10)
});}}
return results;
}
var app = function() {
var result, results,
COLUMN_SEPARATOR = "\t\t";
document.writeln("<pre>");
results = getData();
document.writeln("COURSE" + COLUMN_SEPARATOR + "GRADE" + COLUMN_SEPARATOR + "HOURS");
for (var i = 0, j = results.length; i < j; i++) {
result = results[i];
document.writeln(result.course + COLUMN_SEPARATOR + result.grade + COLUMN_SEPARATOR + result.creditHours);
}
document.writeln();
computeGPA(results);
document.writeln("</pre>");
}
window.onload = app;
</script>
<body>
</body>
</html>
Removed (below the split): if(input=="")
Added (above the split): if (input === "") { break; }
This should do it:
function getData() {
var input = 0,
results = [];
while (input !== "") {
input = prompt("Enter course name, grade and credit hours (e.g., 'CS3520 A 4' or click OK with no data to terminate.");
if (input === "") { break; }
input = input.split(" ");
results.push({
course: input[0].trim(),
grade: input[1].trim(),
creditHours: parseInt(input[2], 10)
});
}
return results;
}
var app = function () {
var result, results,
COLUMN_SEPARATOR = "\t\t";
document.writeln("<pre>");
results = getData();
document.writeln("COURSE" + COLUMN_SEPARATOR + "GRADE" + COLUMN_SEPARATOR + "HOURS");
for (var i = 0, j = results.length; i < j; i++) {
result = results[i];
document.writeln(result.course + COLUMN_SEPARATOR + result.grade + COLUMN_SEPARATOR + result.creditHours);
}
document.writeln();
document.writeln("</pre>");
}
But i think that this would be an even better solution:
function getData() {
var input = true,
results = [];
while (input) {
input = prompt("Enter course name, grade and credit hours (e.g., 'CS3520 A 4' or click OK with no data to terminate.");
if (!input) { break; }
input = input.split(" ");
results.push({
course: input[0].trim(),
grade: input[1].trim(),
creditHours: parseInt(input[2], 10)
});
}
return results;
}
var app = function () {
var result, results,
COLUMN_SEPARATOR = "\t\t";
document.writeln("<pre>");
results = getData();
document.writeln("COURSE" + COLUMN_SEPARATOR + "GRADE" + COLUMN_SEPARATOR + "HOURS");
for (var i = 0, j = results.length; i < j; i++) {
result = results[i];
document.writeln(result.course + COLUMN_SEPARATOR + result.grade + COLUMN_SEPARATOR + result.creditHours);
}
document.writeln();
document.writeln("</pre>");
}
Because the return value of canceled prompt() depends on the browser. In most browsers the return value is null. However, some very old browsers (e.g. early versions of IE) used to return '' (an empty string).
So instead of using something like if (input != '' && input != null), just use true or false.
User pressed OK, but the input field was empty input === ""
User typed something and hit OK (or enter) input == true
User pressed CANCEL input == null or input == ""
UPDATE
About the textarea thing, try something like this (i didn't test it):
textareaContentByLines = textareaContent.split("\n");
for(index = 0; index < textareaContentByLines.length; index++){
input = textareaContentByLines.split(" ");
results.push({
course: textareaContentByLines[index][0].trim(),
grade: textareaContentByLines[index][1].trim(),
creditHours: parseInt(textareaContentByLines[index][2], 10)
});
}

Comparing array elements to character

I'm trying to write a simple javascript program to check if a letter is a vowel. The problem is the output is incorrect and should say that " a is a vowel."
Javascript:
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
HTML:
<script>
$(document).ready(function() {
findvowel("a",["a","e","i","o","u"]);
});
</script>
Output:
a is a consonant
Add break to your loop so it doesn't keep going.
function findvowel(letter1, vowels) {
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
break;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
}
You can actually use return false; to stop your function right away when a vowel is matched, however in normal cases break will be used because there might be other codes going on after the loop.
BTW:
function findvowel(letter){
//thanks p.s.w.g for reminding me []
return letter+" is a "+(/[aeiou]/i.test(letter)?"vowel":"constant");
}
You're testing the vowel in the for-loop and updating the output every time. So the output will only display if the last vowel that was tested matched the input. Instead, you should break out of the for-loop if a vowel is found, and only display a failure (" is a consonant") after you've tested all the vowels and you weren't able to find a match:
var count = vowels.length;
for (var i = 0; i < count; i++) {
if (vowels[i] === letter1) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
return;
}
}
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
But this method could be simplified to:
function findvowel(letter1) {
var isVowel = "aeiou".indexOf(letter1) > -1;
var message = letter1 + " is a " + (isVowel ? "vowel" : "consonant");
document.getElementById('exercise3').innerHTML = message;
}
This is what I would do, using native functions:
var letter = "a";
var isVowel = ["a","e","i","o","u"].some(function(vowel){
return vowel === letter;
});
Rergarding your message, I would try something like:
var message = letter + (isVowel ? " is a vowel" : " is a consonant");
I would pass in an object instead of an array and take advantage of the constant time lookup using the 'in' keyword. No need for a loop.
function findvowel(letter1, vowels) {
if (letter1 in vowels) {
var message1 = " is a vowel";
document.getElementById('exercise3').innerHTML = letter1 + message1;
} else {
var message2 = " is a consonant";
document.getElementById('exercise3').innerHTML = letter1 + message2;
}
}
then
var obj = {'a': true, 'e': true, 'i': true, 'o': true, 'u': true}
then call it
findvowel('a', obj)
Since you're already using jQuery, which offers $.inArray(), why don't you do this?
var vowels = ["a", "e", "i", "o", "u"];
$(document).ready(function() {
var letter = 'u';
var found = $.inArray(letter, vowels) > -1;
if(found) {
console.log(letter + ' is a vowel');
} else {
console.log(letter + ' is a consonant');
}
});

I have working Javascript code that that converts any number entered into its text equivalent

For example, 4 is converted to "Four" and 33333 is converted to "Thirty three thousands three hundred and thirty three". I am thinking of using JQUERY instead of plain JAVASCRIPT.
Here is the code in its entirety:
<script language="javascript" type="text/javascript">
function NumberToTextConverter()
{
this.TEN = 10;
this.HUNDRED = 100;
this.THOUSAND = 1000;
this.MILLION = 1000000;
this.BILLION = 1000000000;
this.wordList = new Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "TEN", "ELEVEN", "Twelve", "Thirteen", "Fourteen", "fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen");
this.wordList2 = [];
this.initializeTwentys(); // this would populate the twentys
}
NumberToTextConverter.Convert = function(number)
{
var currentConverter = new NumberToTextConverter();
return currentConverter.Convert(number);
};
NumberToTextConverter.prototype.Convert = function(number)
{
var quotient = Math.floor(number / this.BILLION);
var remainder = number % this.BILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.BILLION)
{
return converter.ConvertToMillions(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " billions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " billions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " billions ";
}
realValue = realValue + converter.ConvertToMillions(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertToMillions = function(number)
{
var quotient = Math.floor(number / this.MILLION);
var remainder = number % this.MILLION;
var word = "";
var realValue = "";
var converter = this;
if (number < this.MILLION)
{
return converter.ConverToThousands(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " millions ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " millions ";
}
else
{
realValue = realValue + this.wordList[quotient] + " millions ";
}
realValue = realValue + converter.ConverToThousands(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConverToThousands = function(number)
{
var quotient = Math.floor(number / this.THOUSAND);
var remainder = number % this.THOUSAND;
var word = "";
var realValue = "";
var converter = this;
if (number < this.THOUSAND)
{
return converter.ConvertHundreds(number);
}
else
{
var quotientValue = quotient.toString();
if (quotientValue.length == 3)
{
realValue = realValue + converter.ConvertHundreds(quotient) + " thousands ";
}
else if (quotientValue.length == 2)
{
realValue = realValue + converter.ConvertToDoubleDigit(quotient) + " thousands ";
}
else
{
realValue = realValue + this.wordList[quotient] + " thousands ";
}
realValue = realValue + converter.ConvertHundreds(remainder);
}
return realValue;
};
NumberToTextConverter.prototype.ConvertHundreds = function(number)
{
var quotient = Math.floor(number / this.HUNDRED);
var remainder = number % this.HUNDRED;
var word = "";
var converter = this;
if (number >= 100)
{
return this.wordList[quotient] + " hundred " + converter.ConvertToDoubleDigit(remainder);
}
else
{
return converter.ConvertToDoubleDigit(remainder);
}
};
NumberToTextConverter.prototype.initializeTwentys = function()
{
this.wordList2[0] = "";
this.wordList2[1] = "TEN";
this.wordList2[2] = "TWENTY";
this.wordList2[3] = "THIRTY";
this.wordList2[4] = "FOURTY";
this.wordList2[5] = "FIFTY";
this.wordList2[6] = "Sixty";
this.wordList2[7] = "Seventy";
this.wordList2[8] = "Eighty";
this.wordList2[9] = "Ninety";
};
NumberToTextConverter.prototype.ConvertSingleDigit = function(number)
{
return this.wordList[number];
};
NumberToTextConverter.prototype.ConvertToDoubleDigit = function(number)
{
var quotient = Math.floor(number / this.TEN);
var remainder = number % this.TEN;
var word = "";
if (number > 19)
{
switch (quotient)
{
case 2: word = this.wordList2[2]; break;
case 3: word = this.wordList2[3]; break;
case 4: word = this.wordList2[4]; break;
case 5: word = this.wordList2[5]; break;
case 6: word = this.wordList2[6]; break;
case 7: word = this.wordList2[7]; break;
case 8: word = this.wordList2[8]; break;
case 9: word = this.wordList2[9]; break;
}
return word + " " + this.wordList[remainder];
}
else
{
return this.wordList[number];
}
};
function PleaseConvert()
{
var value = document.getElementById("txtNumberInput").value;
var checkValue = NumberToTextConverter.Convert(parseInt(value));
var currentSpanTag = document.getElementById("spanText");
currentSpanTag.style.backgroundColor = '#aadd88';
currentSpanTag.style.border = 'dotted 1px #333377';
currentSpanTag.innerHTML = checkValue;
}
Your opinions and ideas are appreciated!! My Question is whether it would be good idea to spend time by implementing this logic using JQUERY? Here is the working code :
http://www.coolaspdotnetcode.com/Web/JavaScriptInfoAndCode.aspx
What exactly do you mean by "convert to jQuery code"? jQuery has really pretty much nothing to do with the code you posted. It is not a different language, it has no magic that will make the Javascript any different. jQuery is a library intended to make it easy to manipulate DOM elements and perform common Javascript tasks cross-browser. It is Javascript, and there's nowhere really where it would fit to have a function such as this one.
If what you really mean is "make a plugin out of this", then it's a 5 liner:
$.fn.humanizeNumber = function() {
return this.each(function() {
$(this).html(CALLTHEFUNCTION($(this).html()));
}
});
Where CALLTHEFUNCTION is whatever is the main function of the code you posted above (I don't really care to go through it and find what it is). That plugin would then let you do this:
$('#myelement').humanizeNumber();
To convert the value in #myelement from "123" to whatever your function returns.
If it's already done this way and it's working I don't see why spending time implementing this in jQuery.
Unless if you want to learn/practice jQuery.
If your code works, then no, don't refactor. Why? Because we don't have much time here, on Earth.
I think a better place for this would be http://refactormycode.com/
Stackoverflow is more geared towards direct Question and Answers, and less for discussions.

Categories

Resources