I have made a vowel counter in pure js but I cannot get the counters to work properly. and i cannot seem to find out where i am going wrong just need a little push or example to know how to fix this if that is ok. Can someone please help me thanks in advance.
This is my HTML:
<h1> Vowel Counter </h1>
Please enter text for your vowel count:
<br>
<textarea id="text" rows="10" style="width: 100%;"></textarea>
<br>
<button onclick="countVowels();">Count Vowels</button>
<p id="result"></p>
This is my Javascript:
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
var arrayOfVowels = ("AEIOU");
// Set up our counters
var countA = 0;
var countE = 0;
var countI = 0;
var countO = 0;
var countU = 0;
// Output the results:
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + arrayOfVowels.length + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + arrayOfVowels.length +countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + arrayOfVowels.length +countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + arrayOfVowels.length +countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + arrayOfVowels.length +countU + "<br />";
}
And a have attached my jsfiddle:
http://jsfiddle.net/Matt1990/3Ckw2/43/
I would recommend using regular expressions instead of loops and so many if conditions. The complexity and maintainability of the code is bad in the above solutions unless you consider regex as not being pure js.
var countA = text.match(/[Aa]/g).length;
This will give you direct count. For finding maxval, use basic sort algorithms to find the max and then assign a css style class to it. That is not a technical problem to solve.
How are you counting the vowels?
Right now it is showing 50 for each vowel count because arrayOfVowels.length = 5 and countA (for example), is simply 0. You aren't adding any numbers together, but you're adding 5 to the string 0 which results in "50".
You simply have no mechanism to count vowels, it's not that your "vowel counter" doesn't work. You set up everything correctly but fail to work through the text and systematically count the vowels. You can improve this code by automatically making the letters lower or upper case, so you don't have to use the or operator to check for both cases. I could've done that fast but I am just too lazy...
This vowel counter will work:
function countVowels() {
var text = document.getElementById("text").value;
var arrayOfLetters = text.split("");
var arrayOfVowels = ("AEIOU");
// Set up our counters
var countA = 0;
var countE = 0;
var countI = 0;
var countO = 0;
var countU = 0;
for(i=0; i < arrayOfLetters.length; i++) {
if (arrayOfLetters[i] == "A" || arrayOfLetters[i] == "a") {
countA ++;
}
if (arrayOfLetters[i] == "E" || arrayOfLetters[i] == "e") {
countE ++;
}
if (arrayOfLetters[i] == "I" || arrayOfLetters[i] == "i") {
countI ++;
}
if (arrayOfLetters[i] == "O" || arrayOfLetters[i] == "o") {
countO ++;
}
if (arrayOfLetters[i] == "U" || arrayOfLetters[i] == "u") {
countU ++;
}
}
// Output the results:
document.getElementById("result").innerHTML = "";
document.getElementById("result").innerHTML += "Total Letters: " + arrayOfLetters.length + "<br />";
document.getElementById("result").innerHTML += "A's: " + countA + "<br />";
document.getElementById("result").innerHTML += "E's: " + countE + "<br />";
document.getElementById("result").innerHTML += "I's: " + countI + "<br />";
document.getElementById("result").innerHTML += "O's: " + countO + "<br />";
document.getElementById("result").innerHTML += "U's: " + countU + "<br />";
}
Related
I'd like to write a JavaScript program that displays a symmetric histogram like this image:
The program should ask the user to enter the number of bars to print and the character to use to draw the bars. The count of characters in the bar needs to be displayed on the right-side of each bar.
The example showed is when I entered # as the character and 13 as the number.
Here's my code:
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let text = "";
let symbolNum = symbol;
while (currentNum <= number) {
text += "<br>" + symbolNum + " " + currentNum;
symbolNum += symbol;
currentNum++;
}
document.write(text + "<br>");
And at last, I only can output the following:
I'd like to know what I can do in order to reverse the loop?
Try this
function SymmetricHistogram(){
const size = 10;
let numberX = 0;
let numberY = 0;
for(let i = size; i>=-size; i--) {
for(let j=size; j>=Math.abs(i); j--){
process.stdout.write("#");
}
numberX <=size ? console.log(numberX++) : console.log(--numberY);
}
}
SymmetricHistogram();
Or try the below
https://onecompiler.com/javascript/3x58bqr3h
Two different way for the same result. Not realy clean, but work.
var symbol = prompt("Enter the symbol");
var number = prompt("Enter the number");
var currentNum = 1;
let textTOP = "";
let textBOTTOM = "";
let symbolNum = symbol;
while (currentNum <= number) {
textTOP += "<br>" + symbolNum + " " + currentNum;
if (currentNum < number)
textBOTTOM = "<br>" + symbolNum + " " + currentNum + textBOTTOM;
symbolNum += symbol;
currentNum++;
}
document.write(textTOP + textBOTTOM + "<br>");
var symbol = '#';
var number = 13;
var currentNum = 1;
let text = "";
while (currentNum < number * 2) {
if (currentNum <= number) {
let num = currentNum;
text += "<br>" + symbol.repeat(num) + " " + num;
} else {
let num = Math.abs(number * 2 - currentNum);
text += "<br>" + symbol.repeat(num) + " " + num;
}
currentNum++;
}
document.write(text + "<br>");
So I'm currently taking a coding class and am not very well versed in coding. I'm having trouble with a getelementbyid block which isn't writing my looped array for an assignment. Could anyone help me out?
Here's the code:
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById(message).innerHTML = "your name is " + input[n] + "<br>"
document.getElementById(message2).innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
Your variables and your id-s have the same names. By doing getElementbyId(message) you are passing the variables' values instead of the fixed id you gave to your elements.
You need to put the id-s in quotes as follows:
document.getElementById("message")
document.getElementById("message2")
Tested at my end and this is working code
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = []
var message = " "
var message2 = " "
var n = 0
var i = 1
var names = n
var grade = i
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name" + names)
message += "Your name is " + input[n] + "<br>"
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value)" + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>"
}
document.getElementById('message').innerHTML = "your name is " + input[n] + "<br>"
document.getElementById('message2').innerHTML = "Grade" + i + " is " + input[i] + "<br"
</script>
</body>
</html>
error:-
The id of getElementbyId must be in quotes
Make sure your selectors are strings
document.getElementById("message"); not document.getElementById(message);
Make sure you end your lines of code with semi-colons. This is not optional even though the code will attempt to run without them.
Change your output to render your accumulated data - right now you're overwriting your output every time you loop.
Note: I don't know what you're doing with the numerical value inside of the prompt methods (names and grade ) so I didn't touch it.
Example:
<!DOCTYPE html>
<html>
<head>
<title>
Looping Assignment
</title>
</head>
<body>
<h1 align=center>Name and Grades</h1>
<p id="message"> Name </p>
<p id="message2"> Grade </p>
<script>
var input = [];
var message = " ";
var message2 = " ";
var n = 0;
var i = 1;
var names = n;
var grade = i;
for (n = 0; n < 1; n++) {
var names = n + 1
input[n] = window.prompt("Enter First Name " + names)
message += "Your name is " + input[n] + "<br>";
}
for (i = 1; i < 5; i++) {
input[i] = window.prompt("Enter Grade (numerical value) " + grade)
message2 += "Grade " + i + " is " + input[i] + "<br>";
}
document.getElementById("message").innerHTML = message + "<br>";
document.getElementById("message2").innerHTML = message2 + "<br>";
</script>
#SlavicMilk
Below should be sufficient for your assignment:
HTML (index.html):
<h1 style="text-align: center">Name and Grades</h1>
<table>
<thead>
<th>Name</th>
<th>Grade</th>
</thead>
<tbody id="data">
</tbody>
</table>
<script src="script.js"></script>
JS (script.js):
let student = []
for (let i = 0; i < 5; i++) {
student[i] = {
"name": window.prompt(`Enter Name ${i + 1}`),
"grade": window.prompt(`Enter Grade (numerical value) ${i + 1}`)
}
}
document.getElementById('data').innerHTML = student.map(student => {
return `<tr><td>${student.name}</td><td>${student.grade}</td></tr>`
})
First I created a version of this which worked where I didn't input the value on the webpage:
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == 3)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
</script>
Then this is the version I'm trying to create where I enter in the input on the webpage, and then the computer tries to guess it, but it's not executing at all or showing anything when I try to debug in the console.
<p>Enter in how many fingers (between 0 and 5) you are holding up: </p>
<p>
<input id="fingersInput" type="text">
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
var numberOfFingers = document.getElementById("fingersInput").value;
var fingersText = "";
var correctGuesses = 0;
document.getElementById("fingersSubmit").onclick = function ()
{
i = 0;
while (i < 5)
{
var computerGuess = Math.floor((Math.random()*5)+1);
fingersText += "<p>" + computerGuess + "</p>";
if (computerGuess == numberOfFingers)
{
var correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById("fingers-game-v2").innerHTML = fingersText;
document.getElementById("computer-guess-results").innerHTML = "<h3>" + "Number of times the computer guessed correctly: " + "</h3>" + correctGuesses;
}
I'm a beginner coder so if there is any useful knowledge pertaining to this in addition to showing me the correct code, then I'd greatly appreciate that!
Thanks!
Here's a working version where I tried to stay as close to your original code as possible:
<html>
<body>
<p>Enter in how many fingers (between 0 and 5) you are holding up:</p>
<p>
<input id="fingersInput" type="text" />
<button id="fingersSubmit">Guess!</button>
</p>
<div id="fingers-game-v2"></div>
<p id="computer-guess-results"></p>
<script type="text/javascript">
document.getElementById('fingersSubmit').onclick = function() {
i = 0;
var fingersText = '';
var correctGuesses = 0;
var numberOfFingers = document.getElementById('fingersInput').value;
while (i < 5) {
var computerGuess = Math.floor(Math.random() * 5 + 1);
fingersText += '<p>' + computerGuess + '</p>';
if (computerGuess == numberOfFingers) {
correctGuesses = correctGuesses + 1;
}
i++;
}
document.getElementById('fingers-game-v2').innerHTML = fingersText;
document.getElementById('computer-guess-results').innerHTML =
'<h3>' +
'Number of times the computer guessed correctly: ' +
'</h3>' +
correctGuesses;
};
</script>
</body>
</html>
The main reason your code wasnt working is because you need to get the input value when the button is clicked (i.e. place it inside the onclick)
The other issue is that you redeclare correctGuesses inside the if block, so you should just remove the var keyword, otherwise you will get NaN
Finally, this isn't strictly a problem with your code, but moving forward you should be aware that numberOfFingers is a string whereas correctGuesses is a number. In your if block, you compare the two values and it works because you used ==, which only checks value. It's typically better practice to use === which is a stricter equality check, comparing both value and type. So moving forward, you might want to make sure to convert numberOfFingers to a number before you do the equality check
Been browsing SO for some time since I picked up a programming course, and have found it to be an awesome community and great place for knowledge.
Currently I'm stuck with a JavaScript function that I'm trying to clean up.
I need to have names input into an array, and then when I run a 'start' function, it would display the amount of names as a number, and then show each name on a new line.
I've managed to get it working, however there is a ',' character at the start of each line. I've tried various ways to get around it (using replace and split + join) but had no luck so far.
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
};
document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName + "<br>");
return custName;}
}
The reason is most likely because you are trying to display arrName which is an Array with this code: document.getElementById("output").innerHTML = "The total names in the array are: " + totalName + "<br />" + arrName;
Here's what I'd suggest:
var arrName = [];
var custName;
function start(){
var totalName = 0;
var count = 0;
document.getElementById("output").innerHTML = " ";
while(count < arrName.length){
totalName++;
count++;
}
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;}
}
Since there is no need for the WHILE Loop, You can skip it like so:
var arrName = [];
var custName;
function start(){
var totalName = arrName.length;
var strOutput = "The total names in the array are: ";
strOutput += totalName + "<br />" + arrName.join("<br />");
document.getElementById("output").innerHTML = " ";
document.getElementById("output").innerHTML = strOutput;
}
function addName(){
custName = document.getElementById("custname").value;
if(!custName){
alert("Empty Name!");
}
else{
arrName.push(custName);
return custName;
}
}
An array when console logged or inserted to DOM directly will be represented as item1,item2,item3,item4
So simply, arrName.join("<br />")
Also, your while loop can be simply replaced by
totalName = arrName.length;
count = arrName.length
Here is my code:
//input variables
var students = [];
var marks = [];
//output variables
var grade = [];
var topMark = 0;
var topStudent = "";
var botMark = 0;
var award = "";
var error = "";
var Acount = 0;
var Bcount = 0;
var Ccount = 0;
var Fcount = 0;
//Getting Name and Mark
var index = 0;
var i = 0;
var name = prompt("Enter student name","Harry");
while (name != ""){
students[index] = name;
index++;
var mark = prompt("Enter Mark " + name)
marks[i] = mark;
i++;
name = prompt("Enter student name", "John");
};
//Getting Grade
function getGrade(mark){
if (mark < 50){
grade = "F";
} else if (mark < 70){
grade = "C";
} else if (mark < 83){
grade = "B";
} else {
grade = "A";
} return grade;
}
// Top Student Function
function topStudent(){
}
// Top Mark Function
function topMark(){
}
// Bottom Mark Function
function botMark(){
}
// A, B, C, and F Count Function
function getCountOf(grades, grade){
var count = 0;
for (var i = 0; i < grades.length; i += 1){
var count = grades[i];
if (grades[i] == grade) {
count += 1;
}
}
return count;
}
//Display Table
document.write("<table>")
document.write("<tr><th>Student</th><th>Mark</th><th>Grade</th></tr>");
for (var i = 0; i < students.length; i++){
document.write("<tr><td>" + students[i] + "</td><td>" + marks[i] + "</td><td>" + getGrade(marks[i]) + "</td></tr>");
}
document.write("</table>");
// Display Bottom
if (students.length > 0){
document.write("<br />");
document.write("<br />");
document.write("Top Student: " + topStudent);
document.write("<br />");
document.write("Top Mark: " + topMark);
document.write("<br />");
document.write("Bottom Mark: " + botMark);
document.write("<br />");
document.write("Number of A Marks: " + getCountOf(grade));
document.write("<br />");
document.write("Number of B Marks: " + getCountOf(grade));
document.write("<br />");
document.write("Number of C Marks: " + getCountOf(grade));
document.write("<br />");
document.write("Number of F Marks: " + getCountOf(grade));
}
I need help with the A, B, C, and F Count Function and how I am displaying it any help is welcome the display bottom is where I try and display the count of each grade A, B, C, and F but it only displays the mark most entered so if there are 3 A's 2 B's and a C it will display A next to all the counts.
As Dan Kuida mentioned, I hope this isn't homework of some kind, but I've changed your code below. I would've given you a JSFiddle to work with, but those sites don't agree with document.write() functions. Here are the two sections you need to change.
// A, B, C, and F Count Function
function getCountOf(grade) {
var count = 0;
for (var i = 0; i < marks.length; i++) { // Could also use marks.forEach() here
if (getGrade(marks[i]) === grade) {
count++;
}
}
return count;
}
You already have the marks saved and a function to convert them! No need for a grades array. Also note the ++ operator instead of the +=
// Display Bottom
if (students.length > 0) {
document.write("<br />");
document.write("<br />");
document.write("Top Student: " + topStudent);
document.write("<br />");
document.write("Top Mark: " + topMark);
document.write("<br />");
document.write("Bottom Mark: " + botMark);
document.write("<br />");
document.write("Number of A Marks: " + getCountOf("A"));
document.write("<br />");
document.write("Number of B Marks: " + getCountOf("B"));
document.write("<br />");
document.write("Number of C Marks: " + getCountOf("C"));
document.write("<br />");
document.write("Number of F Marks: " + getCountOf("F"));
}