Set variable to itself plus another variable in JavaScript - javascript

I made a more complex (albeit only slightly) program in my CS class that ran some calculation and discounts according to some rules. It was written in Java, and read and output to a file. I am trying to redo it in JavaScript with a loop taking in input and applying calculations afterwards. I would call both functions after the second while loop closes.
My problem is that priceCount increments by price perfectly, while qty seems to just spit out somewhat random numbers (they're all multiples of inputs, however) with a leading 0. What's going on here? It's the exact same logic as the priceCount, but simply isn't working. I tried moving variables around, thinking it's a scope issue, but nothing worked.
I hope I'm not asking a question that has been answered many times. I tried searching extensively, but that is a skill in itself, and it is difficult for me to phrase my question into keywords. Any and all input will be greatly appreciated.
function discountCalc (price, amount) {
var discount;
if (amount <= 30){
discount = oldPrice * 0.05;
}
else if (amount >= 30 && amount <= 50){
discount = oldPrice * 0.1;
}
else if (amount >= 51 && amount <= 75){
discount = oldPrice * 0.25;
}
else {
discount = oldPrice * 0.4;
}
return discount;
}
function adjust(newPrice, amount){
var adjust;
if (newPrice < 500){
adjust = -20;
}
else if (newPrice >= 500 && amount < 50){
adjust = newPrice * 0.05;
}
else{
adjust = 0;
}
return adjust;
}
var answer = "new", price, amount, customer = 1;
while (answer !== "quit" && answer !== "Quit" && answer !== "q" && answer !== "Q") {
console.log("invoice # 000" + customer);
if (answer == "new" || answer == "New") {
customer = customer + 1;
var another = "yes";
var priceCount = 0;
var qty = 0;
while (another == "yes" || another == "Yes" || another == "y" || another == "Y"){
price = prompt("price?");
amount = prompt("amount?");
qty = qty + amount;
priceCount = priceCount + (price * amount);
console.log("Price: " + price + " Amount: " + amount);
another = prompt("type yes for another, any key to stop");
}
console.log("Total price is: " + priceCount);
console.log("Total items: " + qty);
priceCount = 0;
qty = 0;
}
answer = prompt("new or quit?");
}
console.log("thanks");

Prompt returns a string, so you should convert it to a number.
You can use parseInt(), parseFloat(), or Number().
parseInt() returns an integer value, and parseFloat() returns a float.
Number() can return both, but if the prompt returns string that doesn't evaluate to numbers, it returns NaN. It can be useful to check if the user is giving invalid data.
So replace
qty = qty + amount
to
qty = qty + Number(amount) //or parseInt(amount), parseFloat(amount)
if you have other areas adding amount to a number, you can do the same.

Related

Javascript : problem with while loop that does not work

In the script below, I'm trying to get a function to find a random number chosen by the system. To help me to find the number :
When the number to find is smaller than what I enter on the interface: I get a message that the number to find is smaller
When the number to find is bigger than the one I enter on the interface: I receive a message that the number to find is bigger
When I find the number, I receive a message telling me that I have found the number in xxx tries. When I find the number in one go, I want to change trial by trial in the message
When I rotate the code below I just have a box to ask me what is the number to guess. Then nothing happens. Can you please help me to fix the code problems in my script below. Could you please also indicate if my approach is correct to count the number of attempts in the code below. How would you proceed ?
function askValue() {
var answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
console.log("Please enter a valid number");
} else {
return answer;
}
}
function guessnumber() {
var secret_number = Math.floor(Math.random() * 10) + 1;
var guess = askValue();
var attempts;
var i = 0;
var resultMessage = "You won, you take";
while (win == false) {
attempts++;
if (guess < secret_number) {
console.log("The secret number is bigger");
i++;
} else if (guess > Secret_number) {
console.log("The secret number is smaller");
i++;
} else if (guess == secret_number) {
win = true;
}
console.log(resultMessage);
}
}
// call the function
guessnumber();
I make your code works by fixing many mistake and bugs some of them:
using var which is old and it's better use the keyword let to declare variable!
checking if the number between 1 & 10: if (+answer < 1 || +answer > 10)
prefix +, is just shorthand for parseInt() function to convert string to number, since prompt return string not number
many more...
if you don't understand sth do a comment and I will explain to you!
function askValue() {
let answer = window.prompt(
"Guess the number, enter a number between 1 and 10"
);
// keep the answer to use it in the loop
if (!answer || isNaN(answer)) {
alert("Please enter a valid number");
} else if (+answer < 1 || +answer > 10) {
alert("Please enter a number between 1 and 10");
} else {
return +answer;
}
}
// Better using `let` than `var`
function guessnumber() {
let secret_number = Math.floor(Math.random() * 10) + 1;
let guess = askValue();
let attempts = 0; //initialse attempts with zero
let i = 0;
let resultMessage = "You won, you take ";
let win = false; //declare win
while (win == false) {
attempts++;
if (guess < secret_number) {
alert("The secret number is bigger");
i++;
guess = askValue();
} else if (guess > secret_number) {
//s lowercase not capital
alert("The secret number is smaller");
i++;
guess = askValue();
} else if (guess == secret_number) {
win = true;
resultMessage += attempts + " attempt" + (i != 1 ? "s" : "");
alert(resultMessage);
} else {
guess = askValue();
}
}
}
// call the function
guessnumber();

Random number upper limit and lower limit

I'm working on a random number guessing game in JavaScript. I want the user to input a lowLimit and a highLimit and have the random number generated between those two numbers. I tried hardcoding the lowLimit and highLimit as below:
let lowLimit = 5;
let highLimit = 20;
let random = Math.floor(Math.random() * highLimit);
if (random < lowLimit) {
random += lowLimit;
}
console.log(random);
and everything works well.
However, when I allow the user to input values, the random number always becomes the sum of lowLimit and upperLimit. I cannot figure this out!
My final code is this:
let lowLimit = prompt('Input the lower limit:');
let highLimit = prompt('Input the upper limit:');
let random = Math.floor(Math.random() * highLimit);
let tries = 0;
if (random < lowLimit) {
random += lowLimit;
}
console.log(random);
let guess = prompt('Secret number generated. Enter guess:');
while (guess !== random) {
if (guess === 'q') break;
tries += 1;
if (guess > random) {
prompt('You guessed too high. Guess again...');
} else if (guess < random) {
prompt('You guessed too low. Guess again...');
} else {
alert('You guessed correctly! You made ' + tries + " guesses.");
}
}
This solution works. Any refactoring suggestions are welcome.
let lowLimit = Number(prompt('Input the lower limit:'));
let highLimit = Number(prompt('Input the upper limit:'));
while (!lowLimit || !highLimit) {
lowLimit = Number(prompt('Input a valid lower limit:'));
highLimit = Number(prompt('Input a valid upper limit:'));
}
lowLimit = Number(lowLimit);
highLimit = Number(highLimit);
let random = Math.floor(Math.random() * (highLimit - lowLimit) + lowLimit);
let guesses = 0;
console.log(random);
guess = prompt('Enter guess:');
while (guess !== random) {
if (guess === 'q') {
alert('Ok. Quitting... You made ' + guesses + ' guesses')
break;
}
guesses += 1;
guess = Number(guess);
if (guess > random) {
guess = prompt('You guessed too high. Guess again...');
} else if (guess < random) {
guess = prompt('You guessed too low. Guess again...');
} else alert('You guessed correctly! You made ' + guesses + " guesses.");
}
A few tweaks to improve the code, and one bug fix (the case where user guesses correctly on the first try, they will receive no feedback)...
// + is concise way to coerce an int
const lowLimit = +prompt('Input the lower limit:');
const highLimit = +prompt('Input the upper limit:');
// note - we could add checks here for invalid or disordered values
// this presumes we want random to be exclusive of highLimit. if not, we'll need to tweak
const random = Math.floor(Math.random() * (highLimit - lowLimit) + lowLimit);
// we'll vary the prompt during the game
let promptMsg = 'Enter guess:', guesses = 0, guess;
// bug fix and cleanup: do while, so we always play at least once
// prompt in just one place, alter the prompt message to represent game state
do {
guess = prompt(promptMsg);
guesses++;
if (guess !== 'q') {
guess = +guess;
if (guess > random) {
promptMsg = 'You guessed too high. Guess again...';
} else if (guess < random) {
promptMsg = 'You guessed too low. Guess again...';
}
}
} while (guess !== 'q' && guess !== random);
const endMsg = guess === 'q' ? 'Ok. Quitting' : 'You guessed correctly.'
const guessesMsg = `You made ${guesses} ${guesses === 1 ? 'guess' : 'guesses'}`;
alert(`${endMsg} ${guessesMsg}`)
We can generate a random number by using the Date.now()
let res = Date.now() % (highLimit - lowLimit + 1) + lowLimit.
This is because nobody can estimate the time in milisecond the code runs.

How do I make a continuous loop for "confirm" alert in javascript

So I'm kinda new to Javascript, so sorry if this question sounds pretty basic. So I'm trying to make a guessing game where the computer guesses the number the user is thinking. I want to make it so that no matter how many times the user clicks "cancel" a new random number will show up until it the computer "guesses" the number the user was thinking. but i cant figure out how to make a loop out of that.
here's my code:
const guesser = () => {
let min = 0;
let max = 100;
let guess;
alert("Think of a number between 0 and 100");
while (min <= max) {
guess = Math.round((min + max) / 2);
if(confirm("is your number " + guess) == false){
if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false){
if (confirm("is your number " + Math.floor(Math.random() * guess)) == true){
alert("haha got your number!")
}
}
else if (confirm("is your number " + Math.floor((Math.random() * 50) + guess)) == true){
alert("haha got your number!")
}
}
else {
alert("haha got your number!")
}
return;
}
alert("I could not guess your number. I think you are cheating!");
};
You ask the user to tell you if their number is higher or lower than your guess, but you need to do something with that information. Specifically, if their number is greater than the current guess, increase the guess by bringing the minimum up to the current guess. If their number is less than the current guess, decrease the guess by bringing the maximum down to the current guess.
function main() {
var min = 0;
var max = 100;
alert(`Think of a number between ${min} and ${max}`);
while (min<max) {
var guess = Math.round((min + max) / 2);
if(confirm("is your number " + guess)) {
alert("haha got your number!")
return;
} else {
if(confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'")) {
min = guess+1;
} else {
max = guess-1;
}
}
}
alert("I could not guess your number. I think you are cheating!");
}
main();
Here is another way to achieve what you're looking for:
document.addEventListener("DOMContentLoaded", function(event) {
const guesser = () => {
let min = 0;
let max = 100;
let guess;
alert("Think of a number between 0 and 100");
while (min <= max) {
// initial guess
guess = Math.round((min + max) / 2);
if (confirm("is your number " + guess) == false) {
if (confirm("if your number is higher, please click 'ok'. If its lower please click 'cancel'") == false) {
// number is lower than guess
max = guess;
} else {
// number is higer than guess
min = guess
}
} else {
alert("guessed your number!")
return
}
}
}
guesser();
});
<html>
<head>
</head>
<body>
Hello World!
</body>
</html>

I'm writing a guessing game in javascript. I don't know how to validate that the number is inbetween 0 and 100 through the code

The exercise I'm doing is to write a guessing game.
It asks for you to write a function for the user to enter a guessed number, write a second function to validate the code, write a third function that checks the number and tells the user if it's too high or too low.
My problem is that when I get to the too high or too low part it stops validating whether the number is in between 1 and 100. I've tried everything that I know and I'm still really confused. The code worked otherwise before I put in the ValidNUm variable.
I feel like this could be an easy answer and I'm not getting it so I'm sorry. point is I need the guessing game to validate the number, if it's wrong they will enter a number till it is correct, then it tells them wether that validated number is too high or too low.
What happened before is that it validates the number but doesn't pass on the valid number to be assessed.
var GuessedNumber, RandomNum, ValidNum;
RandomNum = 24; //Math.floor((Math.random() * 100) + 1);
GuessedNumber = EnterGuess();
ValidNum = ValidateGuess(GuessedNumber);
NumberCheck(GuessedNumber, RandomNum, ValidNum);
function EnterGuess() {
var ArgGuessNum;
ArgGuessNum = parseFloat(prompt("Please guess a number between 1 and 100"));
return ArgGuessNum;
}
function ValidateGuess(ArgGuessNum) {
var ArgValidNum;
while (ArgGuessNum < 1 || ArgGuessNum > 100) {
ArgGuessNum = parseFloat(
prompt("Please guess a valid number between 1 and 100")
);
}
if (ArgGuessNum > 0 || ArgGuessNum < 100) {
ArgValidNum = ArgGuessNum;
return ArgValidNum;
}
alert("valid number");
}
function NumberCheck(ArgGuessNum, ArgRandomNum, ArgValidNum) {
var ctr = 1;
while (ArgValidNum != ArgRandomNum) {
if (ArgValidNum > ArgRandomNum) {
ArgGuessNum = parseFloat(
prompt("Uh-Oh the number is too high! enter another guess")
);
ValidateGuess(ArgGuessNum);
} else if (ArgValidNum < ArgRandomNum) {
ArgGuessNum = parseFloat(
prompt("Uh-Oh the number is too low! enter another guess")
);
ValidateGuess(ArgGuessNum);
}
ctr++;
}
alert("you took " + ctr + " guesses");
}
When you validate the guessed number inside the NumberCheck(...) you are not assigning the resulting 'valid' number back to a variable (so it's never considered in the next iteration of the loop.
You need to add something like ArgValidNum = ValidateGuess(ArgValidNum);
I also went and simplified the NumberCheck(...) since you are comparing only two numbers: the one guessed and the 'randomly' created at the beginning.
See demo code below
var GuessedNumber, RandomNum, ValidNum;
RandomNum = 24; //Math.floor((Math.random() * 100) + 1);
GuessedNumber = EnterGuess();
ValidNum = ValidateGuess(GuessedNumber);
NumberCheck(RandomNum, ValidNum);
function EnterGuess() {
return parseFloat(prompt("Please guess a number between 1 and 100"));
}
function ValidateGuess(ArgGuessNum) {
var ArgValidNum;
while (ArgGuessNum < 1 || ArgGuessNum > 100) {
ArgGuessNum = parseFloat(
prompt("Please guess a valid number between 1 and 100")
);
}
if (ArgGuessNum > 0 || ArgGuessNum <= 100) {
ArgValidNum = ArgGuessNum;
return ArgValidNum;
}
console.log("valid number");
}
function NumberCheck(ArgRandomNum, ArgValidNum) {
var ctr = 1;
while (ArgValidNum !== ArgRandomNum) {
if (ArgValidNum > ArgRandomNum) {
ArgValidNum = parseFloat(
prompt("Uh-Oh the number is too high! enter another guess")
);
ArgValidNum = ValidateGuess(ArgValidNum);
} else if (ArgValidNum < ArgRandomNum) {
ArgValidNum = parseFloat(
prompt("Uh-Oh the number is too low! enter another guess")
);
ArgValidNum = ValidateGuess(ArgValidNum);
}
ctr++;
}
alert("you took " + ctr + " guesses");
}

Number guessing game, relationship between maxGuesses and guess count is skewed by 1

I am trying to let the game only let the user have 3 guesses to guess correctly. The problem is that it lets the user guess a 4th time, but even if user guesses correctly on 4th attempt I get a wrong answer message. I tried changing the number of guesses, changing that i = 0 start position, subtracting one from maxGuesses in the for loop. No matter what I try the relationship is off by one. Here is my code so far.
let readlineSync = require("readline-sync");
let hint = "";
let maxGuesses = 3;
const maxRange = 10;
const minRange = 1;
let userGuess = readlineSync.question(
"I have chosen a number between " +
minRange +
" and " +
maxRange +
". You have " +
maxGuesses +
" tries to guess it!\n"
);
const randomNumber = Math.floor(Math.random() * maxRange + 1);
function handleGuess(userGuess) {
if (userGuess != null && userGuess != undefined && (userGuess <= maxRange && userGuess >= minRange)) {
for (i = 0; i <= maxGuesses - 1; i++) {
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
return;
} else {
if (userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
}
console.log("Dude...YOU SUCK!");
return;
} else {
userGuess = readlineSync.question("Fix your answer fool! \n");
handleGuess(userGuess);
}
}
I assume your first call is handleGuess() with no parameter.
Then, your program asks the user for its first guess (withe the message "Fix your answer fool!"). If you call handleGuess() with a parameter, the following still applies.
After that, the loop will begin.
if the first answer is wrong, the console will display the message "Think [higher/lower] you fool.", and then request the second guess. Still in the first loop iteration.
Do you see where the problem is ?
If the second guess is still wrong, the console will display the second wrong message and request the third guess while still being in the second loop iteration.
Finally, If the third guess is still incorrect, the third "wrong" message will appear and your code will request a fourth guess before ending the loop and display the message "Dude...YOU SUCK!" without verifying your input.
To prevent that, you can do something like this :
function handleGuess(userGuess) {
i = 0;
do {
if(i > 0) {
if(userGuess > randomNumber) {
hint = "Think lower you fool.";
} else {
hint = "Think higher you fool.";
}
console.log(hint);
userGuess = readlineSync.question("Guess again. \n");
}
while(isNaN(userGuess)) {
userGuess = readlineSync.question("Correct you guess. \n");
}
} while(userGuess != randomNumber && i < maxGuesses);
if (userGuess == randomNumber) {
console.log(userGuess + " is CORRECT! YOU WIN!");
} else {
console.log("Dude...YOU SUCK!");
}
}
Just set the condition for your loop to be i < maxGuesses not i <= maxGuesses -1:
var maxGuesses = 3;
for (i = 0; i < maxGuesses; i++) {
console.log("Guess " + (i + 1)); // Only adding 1 here so output is 1-based
}

Categories