Javascript adding to array using readline - javascript

I'm trying to repeatedly get 2 inputs and store them into an array until the word 'end' is typed. However, I'm getting undefined at the console.log(studentList[i]);
EDIT: With the help of you guys, I was able to store the values into the array. Right now what I want to do is to give a 'grade' to each of the marks that was entered. However no matter what number i entered, i was getting 'HD' for all the grades.
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function printList(list) {
for (let i = 0; i < studentList.length; i += 1) {
var grade;
if ((marks <= 100) && (marks => 80)){
grade = 'HD'
studentList[i][2] = grade;
}
else if ((marks <= 79) && (marks => 70))
{
grade = 'D'
studentList[i][2] = grade;
}
else if ((marks <= 69) && (marks =>60))
{
grade = 'C'
studentList[i][2] = grade;
}
else if ((marks <= 59) && (marks =>51))
{
grade = 'P'
studentList[i][2] = grade;
}
else if ((marks < 50) && (marks =>0))
{
grade = 'N'
studentList[i][2] = grade;
}
console.log(studentList[i]);
}
}
function Input()
{
while(true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') {
printList(studentList)
break
}
console.log("Student Name is" , name);
marks = readline.question("Enter marks for " + name + ": ");
if (marks === 'end') {
printList(studentList)
break
}
console.log("Marks for " + name + " is " + marks );
studentList.push([name, marks]);
}
}
Any advice would be much appreciated! Thanks!

You mainly need to change .Length to .length and you have to use a while loop combined with a break (once 'end' is typed) that comes out of the while loop to give you the list you want to print. By changing the location of the if statements you are able to adjust when the break can occur and when it reads from users input.
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function printList(list) {
for (let i = 0; i < list.length; i += 1) {
console.log('list[i]', list[i]);
}
}
function Input()
{
while(true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') {
printList(studentList)
break
}
console.log("Student Name is" , name);
marks = readline.question("Enter marks for " + name + ": ");
if (marks === 'end') {
printList(studentList)
break
}
console.log("Marks for " + name + " is " + marks );
studentList.push([name, marks]);
}
}

I don't think you know how many students there are ahead of time, so you will need to loop until "end" is detected.
This might help:
const readline = require('readline-sync');
var name, marks;
var studentList = [];
Input();
function Input() {
while (true) {
console.log("Please enter the student name (or \"end\" to end): ");
name = readline.question("Student Name: ");
if (name === 'end') break;
console.log("Student Name is", name);
marks = readline.question("Enter marks for " + name + ": ");
console.log("Marks for " + name + " is " + marks);
studentList.push([name, marks]);
}
}
for (var i = 0; i <= studentList.Length; i++) {
console.log(studentList[i]);
}

Related

simple algorithm with indexOf not working in JS

my mission is to find and output, where the tabs/word entered, is placed in the sentence.
the console gives me back that place var is not defined. What should I do? Thank you very much!
var sentence = prompt("Enter you sentence");
var word = prompt("Enter the tabs/word you looking for");
var counter = 0;
var place = stntence.indexOf(word, counter);
if (stntence.indexOf(word) != -1) {
while (place != -1) {
if (place != -1) {
console.log("The place of the word/tab is: " + place);
counter = place++;
} else {
console.log("That's all")
}
}
} else {
console.log("the word/tabs are not exist in the sentence");
}
Beside the typo of stntence !== sentence, you could take the advantage of the counter and use a shortened approach by assigning the place directly in the while condition.
var sentence = prompt("Enter you sentence"),
word = prompt("Enter the tabs/word you looking for"),
counter = 0,
place = -1;
while ((place = sentence.indexOf(word, place + 1)) != -1) {
console.log("The place of the word/tab is: " + place);
counter++;
}
if (counter) {
console.log("That's all");
} else {
console.log("the word/tabs are not exist in the sentence");
}

Wrong output when using a function

I have a function that calculates the price something.
When the age < 5 then price = 0,
when the age < 15 the price = price/2
and when age > 15 the price = price + price*0.15. The first 2 are working fine but the last one has a problem. When for example a put 100 on the price input and 26 on the age input the answer that it gives me is 10015.
<script>
function add(x, y) {
return x+y;
}
function Subtract(x, y) {
return x-y;
}
function Divide(x, y) {
return x/y;
}
function Multiply(x, y) {
return x*y;
}
var plusPrice = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
var plusButton = (function () {
var counter = 0;
return function () {return counter += 1;}
})();
function updateClickCount() {
document.getElementById("clicks").innerHTML = plusButton();
if (document.getElementById("price").value !== '') {
document.getElementById("input").innerHTML = plusPrice();
}
}
function checkInputs() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if( parseInt(price) < 0 || isNaN(parseInt(price))) {
window.alert("Please insert a valid price");
price = '';
}
if(parseInt(age) > 100 || parseInt(age) < 0 || isNaN(parseInt(age))){
window.alert("Please insert a valid age");
age = '';
}
}
function Calculate() {
var price = document.getElementById("price").value;
var age = document.getElementById("age").value;
if (document.getElementById("price").value !== '' && document.getElementById("age").value !== '') {
if (age<5) {
document.getElementById("demo").innerHTML = Subtract(price,price);
} else if (age < 15 && age >= 5) {
document.getElementById("demo").innerHTML = Divide(price,2);
} else {
document.getElementById("demo").innerHTML = add(price,Multiply(price,0.15));
}
} else {
window.alert("Please fill both age and price to calculate the amount you have to pay");
}
}
</script>
<body>
Please enter the price: <br>
<input type="text" id="price"><button onclick="document.getElementById('price').value = ''">Clear input field</button><br><br>
Please enter your age: <br>
<input type="text" id="age"><button onclick="document.getElementById('age').value = ''">Clear input field</button><br><br>
<button onclick="checkInputs(); updateClickCount(); Calculate();">Calculate price</button>
<p id="totalPrice">The total amount you have to pay is: </p><br>
<p id="demo"></p>
<p>Button Clicks: <a id="clicks">0</a></p>
<p>Correct Price Fill Count: <span id="input">0</span></p>
</body>
Apparently, price is a string. Replace
var price = document.getElementById("price").value;
with
var price = parseFloat(document.getElementById("price").value);
The function has already worked for subtraction and division, because operators - and / can't be applied to strings, so JS coerces them to numbers. The +, however, has a string-compatible interpretation (string concatenation), so type coercion doesn't happen.
or do this
var price = Number(document.getElementById("price").value);
In JavaScript the + symbol can be used both for numeric addition and string concatenation, depending on the variables either side. For example,
console.log('value:' + 4); // 'value:4'
console.log(3 + 1); // 4
console.log('value:' + 4 + '+' + 1); // 'value:4+1'
console.log('value:' + 4 + 1); // 'value:41'
console.log('value:' + (3 + 1)); // 'value:4'
console.log(4 + ' is the value'); // '4 is the value
Hence convert your operands to numeric type before proceeding with addition so that they are not concatenated.
Hope this clarifies.

Encode letter to number

I feel like I am failing everything this semester. but I was wondering if you all could help me with a JS project. We have been tasked with essentially converting numbers to letters and vica versa using textareas in HTML. I was able to do the numbers to letters function, but am having difficulties going the other way. what I have for all is:
var $ = function(id) {
return document.getElementById(id);
};
window.onload = function() {
$("btnDecode").onclick = fnDecode;
$("btnEncode").onclick = fnEncode;
$("btnClear").onclick = fnClear;
};
function fnDecode() {
var msg = $("textin").value;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter a message to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var nums = msg.split(",");
var outstr = "";
for(var i=0; i < nums.length; i++) {
var n2 = parseInt(nums[i]);
if (isNaN(n2)) {
outstr += "?";
} else if (isNallN(nums[i])) {
} else if (n2 === 0) {
outstr += " ";
} else if (n2 < 1 || n2 > 26) {
outstr += "?";
} else {
outstr += String.fromCharCode(n2+64);
}
$("textout").value = outstr;
}
}
function isNallN(s) {
//parse string to check all characters are digits
}
function fnEncode() {
var msg = $("textin").value.toUpperCase();
$("textin").value = msg;
if (msg === "") {
$("textin_span").innerHTML = "* Please enter numberse to decode *";
$("textin").focus;
return;
} else {
$("textin_span").innerHTML = "";
}
var c;
var outstr = "";
for (var i=0; i<msg.length; i++);
c = msg.charCodeAt(i);
if (typeof c === "number") {
outstr += "99";
}else if (c === " ") {
outstr += 0;
/*} else if (c[i] >= "A" && c[i] <= "Z") {
outstr += "99";*/
} else {
outstr += String.charCodeAt(c - 64);
}
$("textout").value = outstr;
//var x = msg.charAT(i);
}
obviously isNallN is not complete, but he promised us if we could figure out fnEncode we should be able to do isNallN with no issues (which I am hoping is true lol) What am doing wrong though in fnEncode? Every time I run it, it gives me "99" even when I put letters in.

Compare two string in js and find difference

how to compare two strings purely, and provide specific result such as highlight extra word, wrong word & skip word in 2nd string. for eg.
var x = "This is the first original string in javascript language." </br>
var y = "This is not the first org string in language."
diff = wrong word ="org"<br>
Extra word ="not"<br>
skip word ="javascript"
//here is slice of my code but in some case my program fails
var x = "here is some value of string";
var y = "here is the some val string";
var k=0;
var SkipWrd="";
for(var i=0; i<y.length;i++){
var sktmp="";
var swtmp=0;
for(var j=0; j<=2;j++) {
if(x[k]!="undefined"){
if(y[i]==x[k+j]){
SkipWrd+=sktmp;
skip+=swtmp;
H_wrd += typ_wrd[i]+" ";
org_para+= sktmp+x[k+j]+" ";
k+=j+1;
break;
}
else{
sktmp+= "<mark>"+ x[k+j]+" "+ "</mark>";
swtmp++;
if(j==2 && y[i]!=x[k+j]){
err++;
Err_Wrd+=y[i]+" ";
H_wrd += "<span id='H-Err'>" + typ_wrd[i] + "</span> ";
org_para+="<span id='O-Err'>" +x[k]+" "+ "</span> ";
k++;
}
}
}
}
}
I have used a word by word comparison approach rather than the character by character approach you used. The overall logic is similar.
The below code will work for your example, but there are many more cases that might go wrong.
var x = "This is the first original string in javascript language.";
var y = "This is not the first org string in language.";
x=x.split(' ');
y=y.split(' ');
var i=0,j=0;
while (1) {
if (!x[i] || !y[j]) break;
if (x[i] == y[j]) {
i++;
j++;
continue;
}
if (x[i] == y[j+1]) {
console.log('Extra word : ', y[j]);
i++;
j+=2;
continue;
}
if (x[i+1] == y[j]) {
console.log('Skip word: ', x[i]);
i+=2;
j++;
continue;
}
if (x[i+1] == y[j+1]) {
console.log('Wrong word: ', y[j]);
i++;
j++;
continue;
}
}

Javascript(Function to compare objects)

I am trying to create a function which will compare one music album to another but my code does not run. I'd like to know why, because I really cannot see where the problem is and why there is a problem. Thanks very much.
/********* GLOBAL VARIABLES *********/
var BR = "<br />";
var ES = " ";
/********* FUNCTIONS *********/
function compare(album[0], album[1]) {
var sameAlbums = false;
//There has to be an easier way to do all this...
if (album[0].artistName === album[1].artistName && album[0].albumTitle === album[1].albumTitle && album[0].releaseYear === album[1].releaseYear && album[0].ifHQ === album[1].ifHQ && album[0].tracks[0] === album[1].tracks[0] && album[0].tracks[1] === album[1].tracks[1] && album[0].tracks[2] === album[1].tracks[2] && album[0].tracks[3] === album[1].tracks[3] && album[0].tracks[4] === album[1].tracks[4] && album[0].tracks[5] === album[1].tracks[5] && album[0].tracks[6] === album[1].tracks[6] && album[0].tracks[7] === album[1].tracks[7] && album[0].tracks[8] === album[1].tracks[8] && album[0].tracks[9] === album[1].tracks[9] && album[0].tracks[10] === album[1].tracks[10])
{
sameAlbums = true;
}
return sameAlbums;
}
/********* MAIN *********/
function main() {
var alb = new album(2);
for (var i = 0; i < album.length; i++) {
album[i] = {
artistName: "",
albumTitle: "",
releaseYear: 0,
ifHQ: "",
tracks: undefined //tracks here
};
album[i].artistName = prompt("What is the artist's name?");
album[i].albumTitle = prompt("What is the album title?");
album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
album[i].ifHQ = prompt("Is the album high quality? Y/N");
while (!(album[i].ifHQ === "Y" || album[i].ifHQ === "N" || album[i].ifHQ === "YES" || album[i].ifHQ === "NO")) {
album[i].ifHQ = prompt("You have entered an invalid response. Is " + album[i].title + " a ifHQ album, Y/N?");
album[i].ifHQ = album[i].ifHQ.toUpperCase();
}
if (album[i].ifHQ === "Y") {
album[i].ifHQ = true;
}
else {
album[i].ifHQ = false;
}
album[i].tracks = new albumay(10);
for (var j = 0 + 1; j < album[i].tracks.length; j++) {
album[i].tracks[j] = prompt("Enter track" + (j + 1));
}
}
for (var key in album[0]) {
document.write(key + ": " + album[0][key] + " ");
document.write(BR);
}
for (var key in album[1]) {
document.write(key + ": " + album[1][key] + " ");
document.write(BR);
}
}
var same = compare(album[0], album[1]);
document.write(same);
// This line calls main, don't change it:
main();
Edited code:
<script type="text/javascript">
/********* GLOBAL VARIABLES *********/
var BR = "<br />";
var ES = " ";
var album = [];
/********* FUNCTIONS *********/
function compare(album1, album2)
{
for (var i in album1)
{
if (album1[i] !== album2[i]) return false;
}
return true;
}
/********* MAIN *********/
function main()
{
var album = [];
var numAlbums = 3;
for (var i = 0; i < numAlbums; i++) {
album[i] = {
artistName: "",
albumTitle: "",
releaseYear: 0,
ifHQ: "",
tracks: undefined //tracks here
};
album[i].artistName = prompt("What is the artist's name?");
album[i].albumTitle = prompt("What is the album title?");
album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
album[i].ifHQ = prompt("Is the album high quality? Y/N");
while (!(album[i].ifHQ === "Y" || album[i].ifHQ === "N" || album[i].ifHQ === "YES" || album[i].ifHQ === "NO"))
{
album[i].ifHQ = prompt("You have entered an invalid response. Is " + album[i].title + " a ifHQ album, Y/N?");
album[i].ifHQ = album[i].ifHQ.toUpperCase();
}
if (album[i].ifHQ === "Y")
{
album[i].ifHQ = true;
}
else
{
album[i].ifHQ = false;
}
album[i].tracks = new album(10);
for (var j = 0 + 1; j < album[i].tracks.length; j++)
{
album[i].tracks[j] = prompt("Enter track" + (j + 1));
}
}
for (var key in album[1])
{
document.write(key + ": " + album[1][key] + " ");
document.write(BR);
}
for (var key in album[2])
{
document.write(key + ": " + album[2][key] + " ");
document.write(BR);
}
}
var same = compare(album1, album2);
document.write(same);
// This line calls main, don't change it:
main();
</script>
If you run a debugger on your code, you will see that the problem is in the compare function. In particular, argument names cannot contain square brackets.
I would recommend changing your compare function thus:
function compare (album1, album2) {
for (var i in album1) {
if (album1[i] !== album2[i]) return false;
}
return true;
}
Based on your update
Ok there are still plenty of issues with this code.
First and most important, album1 and album2 are not defined before being compared, for 2 reasons.
Main() is not executed until after they run, so album[] has not been defined
album[1] is not the same as album 1
Some more things to think about:
Array indices start at 0 in javascript. Skipping the first index to get your arrays to start at 1 is considered bad practice.
Instead of the 24 prompts you're doing right now, you should probably consider forms for input. 24 prompts in a row will be very annoying for a user.
You probably want a modal window for your HQ verification. Something like this
An attempt at cleaning up the code
I think you should probably rethink some of the choices here, but here's a cleaned up version of the code that at the very least runs:
jsfiddle
<script type="text/javascript">
/********* FUNCTIONS *********/
function compare(album1, album2)
{
for (var i in album1)
{
if (album1[i] !== album2[i]) return false;
}
return true;
}
/********* MAIN *********/
function main()
{
var album = [];
var numAlbums = 2;
for (var i = 0; i < numAlbums; i++) {
album[i] = {};
album[i].artistName = prompt("What is the artist's name?");
album[i].albumTitle = prompt("What is the album title?");
album[i].releaseYear = parseFloat(prompt("What is the album's release year"));
var hq = prompt("Is the album high quality? Y/N")
if(!hq)
{
hq = "";
}
while (true)
{
hq = hq.toUpperCase();
if( hq==="Y" || hq === "YES" )
{
album[i].ifHQ = true;
break;
}
else if( hq ==="N" || hq === "NO" )
{
album[i].ifHQ = false;
break;
}
else
{
hq = prompt(
"You have entered an invalid response. Is " +
album[i].title + " a ifHQ album, Y/N?");
}
}
album[i].tracks = [];
for (var j = 0; j < 10; j++)
{
album[i].tracks[j] = prompt("Enter track" + (j + 1));
}
}
var same = compare(album[0], album[1]);
document.write(same);
}
// This line calls main, don't change it:
main();
</script>

Categories

Resources