JS recognizes that var is String - javascript

I think the JS thought that var num was a String, but I want var num as a number! The problem says 'num' is not defined.
var num = document.getElementById('number').value;
var i = Math.floor(Math.random(0,num));
var c = document.getElementById('chance').value;
function clicked(){
var j = document.getElementById('game').value;
if (i > j){
document.getElementById('demo').innerHTML = "Bigger!";
c -= 1;
document.getElementById('re').innerHTML = "You have " + c + " more chances!";
} else if(num < j){
document.getElementById('demo').innerHTML = "The value is bigger than " + num + "!";
document.getElementById('re').innerHTML = " "
} else if (i < j){
document.getElementById('demo').innerHTML = "Smaller!";
c -= 1;
document.getElementById('re').innerHTML = "You have " + c + " more chances";
} else if (i == j){
document.getElementById('demo').innerHTML = "Correct!";
c = 14;
document.getElementById('re').innerHTML = " ";
i = Math.floor(Math.random()*num);
}
if (c == 0){
document.getElementById('demo').innerHTML = "Try again! The secret number was " + num;
c = 14;
document.getElementById('re').innerHTML = " ";
i = Math.floor(Math.random()*101);
}
}
<p>
You should guess a number between 0 ~ <input type="number" id="number"> under this text. You have total <input type="number" id="chance"> chances. Good luck!<br><br>
<input type="number" id="game"> <input type="submit" onclick="clicked()" value="GUESSED">
<p id="demo"></p>
<p id="re"></p>
</p>
I want an ID 'number' be var num, the random number between 0 and num:
which will be the var I, and an ID 'chance' be var c, the number of chances be the c. I hope you know what I mean, because I described precisely as I can. By the way, I am coding a number guessing game HTML and I am a coding nooooob. If you are nice, please help me out. Thank You.

See doc : https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/
var num1 = parseInt(num, 10);
The parseInt() method converts a string into an integer (a whole number).
It accepts two arguments. The first argument is the string to convert. The second argument is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10.
The Number() method converts a string to a number.
Sometimes it’s an integer. Other times it’s a point number. And if you pass in a string with random text in it, you’ll get NaN, an acronym for “Not a Number.”
As a result of this inconsistency, it’s a less safe choice than parseInt() and parseFloat(). If you know the format of the number you’d like, use those instead. If you want the string to fail with NaN if it has other characters in it, Number() may actually be a better choice.

var num = document.getElementById('number').value always returns a string value. You can cast the value using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
num = Number(num);

Related

JavaScript program to convert binary to decimal

I am trying to make a program which is able to do both decimal to binary and binary to decimal conversions.
I am having trouble with the binary to decimal portion of the code. Forgive me as I know the coding is quite incomplete but I can't figure out where I am going wrong.
Currently I am getting partially correct output in the calculation field (ex. "there is a 1 in the value of (2^0)" and "there is a 2 in the value of (2^1)").
However, when I type 11 as decimal the calculation field is repeating the code twice
(ex. "there is a 1 in the value of (2^0)","there is a 2 in the value of (2^1)","there is a 1 in the value of (2^0)", "there is a 2 in the value of (2^1)").
Obviously it should only give those values once per number.
Also the output field for the actual binary number is incorrect as well, and some of the variables aren't utilized/not needed, but I have been trying to fix the problem of repeating values first before I worked on that.
Any help would be much appreciated!!
function convertByArray(bval) {
var rB = new Array();
var outstr = "";
var p, t, a, o;
o = 0;
for(var i=0; i<bval.length; i++) {
var b = bval.charCodeAt(i);
t = 2;
p = i;
a = t ** p;
if(a === t ** p) {
outstr += a;
}
var bV = b;
$("txtCalc").value += "There is a " + a + " in the value " + "(" + t + "^" + p + ")" + "\n";
o += 1;
b = bV;
$("txtOut").value = outstr;
}
}
You can simply your code if you access the most-significant bit of the bit-string by taking the length (minus one) and subtracting it from the current position. You can access string characters like an array.
var $txtCalc = $(".txtCalc");
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function binaryToDecimal(bval) {
var base = 2, result = 0;
for (var pos = 0; pos < bval.length; pos++) {
var bit = +bval[(bval.length - 1) - pos];
if (bit === 1) {
result += base ** pos;
}
var message = "There is a " + bit + " in the position (" + base + "^" + pos + ")";
$txtCalc.val($txtCalc.val() + message + "\n");
}
$txtOut.val(result);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />
<br />
<textarea class="txtCalc" rows="10" cols="60"></textarea>
Alternatively, you can simply your program to the following. In JavaScript, you can parse any number in any base and format to another base.
var $txtOut = $(".txtOut");
binaryToDecimal("10010101"); // 149
function convertFromBaseToBase(number, fromBase, toBase) {
return parseInt(number, fromBase).toString(toBase);
}
function binaryToDecimal(bval) {
$txtOut.val(convertFromBaseToBase(bval, 2, 10));
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="txtOut" />

JS for-loop how to get the first value

I'm sorry for the dumb question. I've been trying to do this for hours now, and i really can't get it to work. So i have a for-loop that loops though some numbers.
But it doesn't take the first value(71990000).
How can this be achieved?
This is what i've got so far:
var minNr = 0000;
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max)
{
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;)
{
if(regex.test(guld_nr))
{
$(".resultat").append(prefix + "" + guld_nr + "<br>");
}
guld_nr++;
}
}
The output is this:
71991010
71991111
71991212
71991313
But i also need the number: 71990000
How can i do that ?
It's because your regex is rejecting the number 0; the first time through the loop, minNr has the numeric value 0 (setting it to 0000 doesn't help; it's just a fancy way of saying 0). The regex expects two digits followed by the same pattern, but what you're giving it is the string '0'.
You could set minNr to be a string instead on the first pass through ('0000'), and this will solve the problem for '0000', but you will miss '0101', '0202', etc. (which will convert to the strings '101', '202', and so on.)
One solution would be to zero pad the string representation of your number. The following function will take any number and left zero pad it to fit a given width:
function zeropad(n, w) {
n = String(n);
while(n.length < w) n = '0' + n;
return n;
}
You can use it to convert minNr for the regex:
regex.test(zeropad(guld_nr, 4))
Also note that Number is a built-in object wrapper for literals in JavaScript (all of the primitives have object wrappers: Number, Boolean, String), and by creating a function called Number, you are occluding this built-in object, which is inadvisable (code that needs to use it will invoke your function instead, which is incompatible and has a different purpose).
Use string:
var minNr = '0000';
It's the start value for the regex test, and you need the four zeroes for that. If it would be a number, then you get only one zero for testing. it would help, if you pad it with leading zeroes.
var minNr = '0000',
maxNr = 10000,
prefix = 7199;
function Nummer(min,max) {
var regex = /^(\d{2})\1$/;
var guld_nr;
for(guld_nr = minNr; guld_nr < maxNr;guld_nr++) {
if(regex.test(guld_nr)) {
document.write(prefix + "" + guld_nr + "<br>");
}
}
}
Nummer(minNr, maxNr);
Numbers don't zero-pad themselves; 0000; // 0
Make a custom zero-pad method for it so you can do zpad(0, 4); // "0000"
function zpad(x, digits) {
var pad = '0';
x = x.toString();
digits -= x.length;
while (digits > 0) {
if (digits & 1) x = pad + x;
pad += pad;
digits >>>= 1;
}
return x;
}
Now adjust Nummer accordingly
function Nummer(min, max, prefix) {
var regex = /^(\d{2})\1$/,
i, str;
prefix = prefix || '';
for(i = min; i < max; ++i) {
str = zpad(i, 4);
if(regex.test(str)) console.log(prefix + str);
}
}
and use
Nummer(minNr, maxNr, '7199');
Side note
Nummer is not constructing an Object, consider camel casing it
You could use arithmetic to do the digit pattern check, and keep the result numerical:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
for (var guld_nr = min; guld_nr < max; guld_nr++) {
if (Math.floor(guld_nr/100) === guld_nr % 100 ) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>
The problem with your code is when the lower numbers are tested against the regular expression, they are implicitly converted to string, and do not get prefixed zeroes, so they fail on the regular expression.
Anyway, the code will be more efficient when sticking to numbers instead of strings, so I would suggest working with numbers all the way up to the point of outputting them in the browser.
Even more efficient is this code:
var minNr = 0; // it does not help to put 4 zeroes here.
var maxNr = 10000;
var prefix = 7199;
function Nummer(min,max) {
var test = Math.floor(min/100)*100 + Math.floor(min/100)%100;
var guld_nr = test < min ? test + 101 : test;
for (; guld_nr < max; guld_nr+=101) {
$(".resultat").append((prefix * 10000 + guld_nr) + "<br>");
}
}
Nummer(minNr, maxNr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="resultat"></div>

JavaScript OnClick Method

I was having trouble with the OnClick method I was learning while creating a game. Every time I enter the value and click the button, it is stuck in a loop, I tried document.write and it works using that, but than it opens a new page instead of showing up on screen.
I am new to the programming community, so any help would be nice.
<body>
<p>Enter an integer between 1-100 here:
<input id="number" type="text" />
</p>
<p>
<button onclick="onclickFunction()" type="button">Enter</button>
</p>
<p id="result"></p>
<script type="text/javascript">
function onclickFunction() {
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
var intNumber;
var count = 0;
var bool = false;
do {
do {
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
if (intNumber > c) {
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
} else if (intNumber < c) {
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
} else if (intNumber == c) {
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
count = count + 1
} while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
</script>
</body>
Updated:
<script type="text/javascript">
// Declare all your functions first
// These functions expect no parameters and return values.
function onclickFunction()
{
var a = Math.random();
var b = a * 100;
var c = Math.floor(b);
// Input from text box.
var randomNumber = document.getElementById("number").value;
// Output to paragraph.
if (randomNumber < c && randomNumber != c)
{
document.getElementById("result").innerHTML = "Too Low " + "</br>";
}
else if (randomNumber > c && randomNumber != c )
{
document.getElementById("result").innerHTML = "Too High" + "</br>";
}
else if (randomNumber == c)
{
document.getElementById("result").innerHTML = "Win!";
}
// Clear text box for further input.
document.getElementById("name").value = "";
}
</script>
<p>Enter an integer between 1-100 here: <input id="number" type="text" /></p>
<p><button onclick="onclickFunction()" type="button">Enter</button></p>
<p id="result"></p>
</body>
First of all, it is always useful to create a fiddle.
That way people who are reading your question can run your code immediately.
Let's break down the code
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
This can be done in a single line, to save variables.
do
{
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
I'm not a big fan of using do/while loops this way, although it can come handy when you want to run the do code at least once, like now.
This loop keeps running when the number is bigger than 100, or smaller than 0. So if I pick an incorrect number that means my browser crashes.
if (intNumber>c){
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
}else if (intNumber<c){
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
}else if (intNumber == c){
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
First you are checking if the guess is bigger than the answer, than if it's smaller. That means that the last check if it's equal is unnecessary, since that is the only option left. You can just use an else here.
Also try to be consistent with your spacing and where you place your curly brackets.
do{
//Stuff
}
and
do
{
//Stuff
}
Are both valid ways to use brackets, but stick to one style or your code will get too confusing.
count = count + 1
A small oversight here is that the count starts at 0. So when you guess the number in a single try, it will say you have done it in 0 tries.
while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
All the previous code will be done until bool becomes true. The problem here is that if I entered a wrong number (or an invalid number). The program will keep running the if statement which requires a lot of computer power since it never stops. It is impossible to change your guess and the page crashes, because the browser is stuck in the while loop.
The simplest solution for this is to calculate if the new guess was correct when the player inputs a new number. So when onClickFunction is called again.
That way you never have to use a while loop. Although you have to calculate the random number somewhere else.
I hope that helped, if you have any question let me know!

Trying to get my JavaScript to work out the 2 numbers entered to get calculated by pc.

Just wondering if anyone can work out why I keep getting for eg. 3+3=33 and not 6.
The rest of the coding works fine for the divide and times its the addition that keeps stuffing up and wont come up with the correct answer.. please help if you can.
here is my code:
<html>
<head>
<title>Practical Task 8 </title>
</head>
<body>
<button onclick="myFunction()">Press & Enter First Digit & Second Digit</button>
<script type="TEXT/JavaScript">
function myFunction()
{
var x=prompt("Please enter first number","0");
var y=prompt("Please enter second number","0");
var sum = x;
var sum2 = y;
var n = (x * y);
var n2 = (x / y);
var n3 = (x + y);
document.write(sum + " + " + sum2 + " = " + n3);
document.write("<BR>" + sum + " * " + sum2 + " = " + n);
document.write("<BR>" + sum + " / " + sum2 + " = " + n2);
}
</script>
</body>
</html>
You're performing string concatenation, not integer addition.
Use parseInt first:
x = parseInt( x, 10 );
y = parseInt( y, 10 );
MDN recommends always specifying the radix (the 10 part) to avoid problems, such as if a user prepends a number with 0 (where it'll be parsed as octal), or if different browsers have a different default radix (wtf, I know!).
You have to do this because the output of prompt is always a string, even if it's a number (e.g. "10" or "0123"), you need to tell JavaScript to interpret the data as a number (use parseInt if it's an integer (a whole number), or use parseFloat if you'll accept numbers with decimal places). Confusingly the + operator works for both string and number types, where it performs either concatenation (i.e. joining strings together like glue) or addition depending on the type of its operands.
Because your code is adding strings.
User input is always string.
You need to parseInt(x, 10) and parseInt(y, 10) to parse the string value into int base 10.

convert string of letters to numbers and add a zero before javascript

I need to write a javascript program that will ask the user to enter a string of lower‐case
characters and then print its corresponding two‐digit code. For example, if
the input is “home”, the output should be 08151305.
So far I can get it to return the correct numbers, but I cannot get it to add the zero in front of the number if it is a single digit
This is what I have:
<html>
<head>
<script type="text/javascript">
function show_prompt()
{
var name = prompt("Please enter a string of lowercase characters");
document.write(name,'<br>');
document.write('Length of the input is ', name.length,'<br>');
document.write("<br>")
for (i=0; i < name.length; i++)
{
{
document.write(i, ", ",name.charCodeAt(i) - 96, '<br>');
}
}
}
</script>
</head>
<body>
<input type="button" onClick="show_prompt()"value="CSE 201 HW#4 Problem 3"/>
</body>
</html>
Well you can just check if it is a single digit and if so prepend "0":
function padToTwoDigits(c) {
// convert to string and check length
c = "" + c;
return c.length === 1 ? "0" + c : c;
// or work with it as a number:
return c >=0 && c <=9 ? "0" + c : c;
}
// then within your existing code
document.write(i, ", ",padToTwoDigits(name.charCodeAt(i) - 96), '<br>');
Of course those are just some ideas to get you started. You can pretty that up somewhat, e.g., you might create a more generic pad function with a parameter to say how many digits to pad to.
You can write your own pad function such as:
function pad(number) {
return (number < 10 ? '0' : '') + number
}
and use the pad function like:
document.write(i, ", ",pad(name.charCodeAt(i) - 96), '<br>');
Try this.
function show_prompt() {
var name = prompt("Please enter a string of lowercase characters");
document.write(name, '<br>');
document.write('Length of the input is ', name.length, '<br>');
document.write("<br>")
for (i = 0; i < name.length; i++) {
var n = name.charCodeAt(i) - 96;
document.write(i, ", ", n < 10 ? "0" + n : n, '<br>');
}
}
I wrote up a quick sample here:
http://jsfiddle.net/ZPvZ8/3/
I wrote up a prototype method to String that handles padding zeros.
String.prototype.pad = function(char, len){
var chars = this.split();
var initialLen = len - this.length;
for(var i = 0; i < initialLen; i++){
chars.unshift(char);
}
return chars.join('');
};
I convert it to an array and then add elements with the padding character. I chose to use an array since performing string manipulations is an expensive operation (expensive in memory and CPU usage).
To use it in your program, you'd just call it like this:
var res = new Array();
for (var i = 0; i < name.length; i++) {
var strCode = (name.charCodeAt(i) - 96).toString();
res.push(strCode.pad('0', 2));
}
document.write(res.join(''));

Categories