I can not reassign a prompt result - javascript

I am trying to solve a tiny program (average of notes) that request via prompt a number. I want that if the input it's not a number, the alert command show a number is needed.
If you check the code, prompt input uses Number() to convert the string to a number. But if I type some string the result is NaN and I tried to reasign the note variable in the while loop but something is wrong because the program continues executing the remaining code.
let subjects = Number(prompt('Type quantity of subjects: '));
let sum = 0;
while (isNaN(subjects)) {
alert('Type a number');
subjects = Number(prompt('Type quantity of subjects: '));
}
for (i = 1; i <= notes; i++) {
note = Number(prompt('Type note of subject' + i + ': '));
sum += note;
}
average = sum / subjects;
alert(average.toFixed(2));
I expect the program ask (via prompt) for a number everytime it's not.

In your code notes is undefined which is used in for loop. I think subjects should be there. And also convert note to Number. And use Unary Plus +. for converting string to number. Its faster.
let subjects = +prompt('Type quantity of subjects: ');
let sum = 0;
while (isNaN(subjects)) {
alert('Type a number');
subjects = +prompt('Type quantity of subjects: ');
}
for (let i = 1; i <= subjects; i++) {
note = +prompt('Type note of subject' + i + ': ');
sum += +note;
}
average = sum / subjects;
alert(average.toFixed(2));

Related

how do I store my prompt input and display all of it when I input zero

let i = -1;
let total = 0;
let numPrompt;
do {
numPrompt = prompt("")
total += parseInt(numPrompt)
i++;
}
while (numPrompt != '0'); // do-while loop
let avg = total/i;
console.log(total)
console.log(avg)
I want user to input a number each time till they input zero which will output all their previous input, total and average.
I declare i = -1 to avoid counting the last input which is the zero.
in my code, I only manage to display the total of all my input but what I also want is all my previous inputs (prompt)printed out each row
You can use an array, which stores a list of things:
let i = 0;
let total = 0;
let numPrompt;
let numbers = [];
do {
numPrompt = prompt("")
total += parseInt(numPrompt)
if (numPrompt != '0') {
numbers.push(numPrompt);
i++;
}
} while (numPrompt != '0'); // do-while loop
let avg = total / i;
console.log(total)
console.log(avg)
console.log(numbers);
Setting i to -1 is a bit of a workaround -- the above code starts it at 0 and checks if the inputted number is 0 before incrementing it.
If you want to store all of your previous inputs, use an array.
let a=[], i, t;
while((i=+prompt())!==0) a.push(i);
console.log(`inputs: ${a}, total: ${t=a.reduce((a,c)=>a+c)}, avg: ${t/a.length}`);

I want to prompt the sum of the numbers prompted before

I am stuck.
I have to prompt a number. and then to create a cycle of prompts related with the intiial prompt and then sum them. I am completely lost. how can I sum them?
let first_question=prompt("introduce the quantity of numbers you want to sum")
for (let i=0; i < first_question;i++)
{
let second_question= prompt ("introduce the number you want to sum");
}
do something like this:
var first_question = parseInt(prompt("Introduce the quantity of numbers you want to sum: "));
var sum = 0;
for (let i = 0; i < first_question; i++) {
let second_question = parseInt(prompt("Introduce the number you want to sum: "));
sum += second_question;
}
and at the end the variable sum will have the value you want.
Also note that prompt() will return a string, so I used parseInt() in order to transform it into a number

Why are these numbers not summing in a for loop using javascript?

I'm iterating over a range, extracting 2 texts (to be converted into numbers) and summing them to put the total back into the stirng later.
However, although I see the numbers logged ok, the sums give me NaN as the results.
Here's the code piece:
var totalPriceToPay = 0;
var totalCODAmount = 0;
if (ss.getActiveSheet().getName() == sheet.getName() && row > 1) {
for (var a = 0; a < dataRng.length; a++) {
if (dataRng[a][1] == true && dataRng[a][0] == 'SHIPPED' && dataRng[a][40] != 'Yes') {
//Isolate the Price to Pay Amounts to be summed and put the total back into the string.
const str = dataRng[a][35].toString();
const priceToPay = str.split(",").slice(8, 9)[0] //Extracts 8th element
totalPriceToPay += Number(priceToPay) //Converts it into a nº and sums to the total
const codAmount = str.split(',').slice(9, 10)[0] //Extracts the 9th element
totalCODAmount += Number(codAmount) //Converts it into a nº and sums to the total
Logger.log('Type Price To Pay: ' + str.split(",").slice(8, 9)[0]);
Logger.log('Type codAmount: ' + str.split(",").slice(9, 10)[0]);
Logger.log('Total Price to Pay: ' + totalPriceToPay);
Logger.log('Total COD: ' + totalCODAmount);
Here are the logs:
Thanks.
The numbers have a $ before it. You need to remove it. Use String.slice:
const priceToPay = Number(str.split(",")[8].slice(1));
The Number() constructor will give NaN when the value cannot be converted to a number. When you add NaN to a number, you get NaN. To avoid the issue, use this pattern:
totalPriceToPay += Number(priceToPay) || 0;
totalCODAmount += Number(codAmount) || 0;

Try to create a for loop that iteratively adds up the sum of its runs in a total variable

I am trying to write a function in Javascript that will return true or false depending on if the number is an Armstrong number or not. Armstrong numbers are numbers that take each digit of a number and multiple it by the length of the number, then add them all up to equal the original number. For example: 153 is an Armstrong number, because: 153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153.
I'm sure my function has other problems and isn't the pretiest but I'm stuck on this.
I've already tried to add parseInt() around multiple areas of the function to ensure that I'm only dealing with integers and not strings without any lucky.
const validate = (num) => {
const numlength = num.toString().length;
let armstrong;
let singleDigit;
for (i = 0; i < numlength; i++) {
singleDigit = num.toString()[i] ** numlength;
armstrong += singleDigit;
}
if (armstrong == num) {
return true;
} else {
return false;
}
};
console.log(validate(153))
The problem that I'm facing is that the armstrong variable is returning NaN for some reason. I'm not quite sure how to iteratively add the singleDigit values that are found in the for statement. When I console.log(singleDigit) right after it is figured out in the for statement, the value is correctly. If I console.log(armstrong) right after that, I get NaN
You need to set initial value of armstrong = 0.
By default it is undefined so when you perform math operation with undefined it results in NaN
const validate = num => {
let numString = num.toString()
const numlength = numString.length;
let armstrong = 0;
let singleDigit = 0;
for (let i = 0; i < numlength; i++) {
singleDigit = numString[i] ** numlength;
armstrong += singleDigit;
}
return armstrong == num
};
console.log(validate(153))
On side note:-
You can simply remove the last if else statement, armstrong == num is already resulting in true or false
Instead of calling toString() on each iteration we can simply store in a variable and use it
One more way is to use reduce instead of for loop
const validate = num => {
let numString = num.toString()
const numLength = numString.length;
const armstrong = [...numString].reduce((acc, r) => acc += r ** numLength, 0)
return armstrong == num
};
console.log(validate(153))

Comparing 2 arrays to output total integer

I have 2 arrays of numbers. I want to go through each array and find the number of times 1 number from each array adds up to the particular amount x.
If the particular amount x is reached as many times as another set number n then the function should print 'YES'. If x does not reach the set number of n then the function should print 'NO'.
The values of x , n and both arrays are in a string input. These values have been split into arrays as seen below in the code.
I have set up 2 for loops to run through each array and an if statement that checks for the condition of x meeting n.
The arrays I'm using in this code should print out the result of 'YES' however every time I run the code I'm getting 'NO' ? I've tried tinkering with the code but nothing has worked.
Any idea on where this code is broke and how to fix the problem?
Thanks :)
code:
var input = '2\n3 10\n2 1 3\n7 8 9';
function processData(input) {
var inputArray = input.split('\n');
var n = inputArray[1][0];
var x = inputArray[1].split(' ')[1];
var arrayA = inputArray[2].split(' ');
var arrayB = inputArray[3].split(' ');
var total = 0;
for(var i = 0; i < arrayA.length; i++) {
for(var j = 0; j < arrayB.length; j++) {
if(arrayA[i] + arrayB[j] == x) {
total = total + 1;
} if (total == n) {
return 'YES';
}
}
}
return 'NO';
}
console.log(processData(input));
arrayA[i] and arrayB[j] are strings, so arrayA[i] + arrayB[j] will be the concatenation of them (ex: '2' + '3' === '23').
If your logic is correct (i didn't quite understand what you are trying to do), it should be enough to convert them to numbers before adding them, using parseInt or some other method:
if(+arrayA[i] + (+arrayB[j]) == +x) { // used unary + to convert to number
total = total + 1;
} if (total == n) {
return 'YES';
}
PS: A cleaner version would be to convert each string in the array to number, but that involves more than adding 3 characters to your code.
PS2: You have a weird way of getting the input data. If you get it from another place in your JS code, you could simply pass it as an object with the relevant structure, otherwise you could pass it around in a more ... common format, like JSON.

Categories

Resources