How to count vowels in a string? - java

The objective is to count how many vowels there are in the phrase that the user inputs.
The user will input a phrase which will be
my name is nic
The output will be for this example is
Vowel Count: 4
Now here is my code.
import cs1.Keyboard;
public class VowelCount {
public static void main(String[] args) {
System.out.println("Please enter in a sentence.");
String phrase = Keyboard.readString();
char[] phraseArray = phrase.toCharArray();
char[] vowels = new char[4];
vowels[0] = 'a';
vowels[1] = 'e';
vowels[2] = 'i';
vowels[3] = 'o';
vowels[4] = 'u';
int vCount = countVowel(phrase, phraseArray, vowels);
System.out.println("Vowel Count: " + vCount);
}
public static int countVowel(String word, char[] pArray, char[] v) {
int vowelCount = 0;
for (int i = 0; i < word.length(); i++) {
if (v[i] == pArray[i])
vowelCount++;
}
return vowelCount;
}
}
With my code I am getting an ArrayIndex Error. I know the fix but when I change
for (int i = 0; i < word.length(); i++) {
to
for (int i = 0; i < 5; i++) {
It fixes the error but does not count the vowels. It outputs
Vowel Count: 0
So how can I fix this problem and is there a better way to do this than the way I am attempting to do it?

Just use regular expression. will save you a lot of time
int count = word.replaceAll("[^aeiouAEIOU]","").length();

You are attempting to store five vowels in a four vowel array;
char[] vowels = new char[5]; // not 4.
vowels[0] = 'a'; // 1
vowels[1] = 'e'; // 2
vowels[2] = 'i'; // 3
vowels[3] = 'o'; // 4
vowels[4] = 'u'; // 5
Or,
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
Also, don't forget to call toLowerCase() or you'll only count lower case vowels.
Finally, you should be looping over each character in pArray and each vowel. I'd use two for-each loops like
for (char ch : pArray) {
for (vowel : v) {
if (ch == v) vowelCount++;
}
}

Related

How do you use charAt with an array?

i am having a bit of trouble in implementing charAt with an array. I am a beginner in Java (and this is my only coding experience i suppose).
The objective: To create a program that the user inputs any string, and the total number of vowels are recorded in the output (case sensitive)
example:
Input: charActer
Output:
a = 1
A = 1
e = 1
import java.util.Scanner;
public class HW5 {
public static void main(String[] args) {
String [] alphabets =
{"aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ"};
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for(int i=0;i<alphabets.length;i++)
{
if(alphabets.charAt[i] == vowels)
*Note: Program is not complete.
You need to check each character of inputStr (dunno what alphabets is about in your code) and see if it can be found in the vowels string.
String vowels = "aAeEiIoOuU";
int found = 0;
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: ");
String inputStr = sc.nextLine();
for (int i = 0; i < inputStr.length(); i++) {
if (vowels.indexOf(inputStr.charAt(i)) >= 0) {
found += 1;
}
}
The documentation is helpful if you're having trouble understanding a method or class.
Having said that, there are lots of ways to count vowels in a String.
Your output indicates that you need the counts per vowel per case, and not just the count of all vowels. To do this you will need a map in order to keep track.
Consider something like
String input = "A string with vowels in it";
Map<Character, Integer> counts = new HashMap<≥();
for (int i = 0; i < input.length; i++) {
char c = input.chart(i);
if (c == 'a') {
int tmp = counts.getOrDefault('a', 0);
tmp++;
counts.put('a', tmp);
} else if (c == 'A') {
// same logic as above for uppercase A
} // other else if statements for e, E, i, I, o, O, u, U
}
// the map has all counts per vowel / case
After the map has all counts you can iterate its entry set to print the output you need
for (Map.Entry<Character, Integer> e : counts. entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}
If you only need the number of values without breaking it down into which vowels, consider something like (not tested)
String vowels = "AaEeIiOoUu";
String input = "Hello World!";
int numVowels = 0;
for (int i = 0; i < input.length; i++) {
char c = input.charAt(i);
if (vowels.indexOf(c) >= 0) {
numVowels++;
}
}
// do something with numVowels
--
Break the problem into simple steps
Define the vowels to look for
Initialize your counter variable (numVowels)
Loop through the input string and check each character against the ones defined in 1 (vowels).
For each vowel you find, increment your counter variable.
public class Vowels {
public static void main(String[] args) {
Map<Character, Integer> vowels = new HashMap<>();
Scanner sc = new Scanner(System.in);
System.out.print("Please enter any word: "); //"charActer";
String str = sc.nextLine();
for (int i = 0; i < str.length(); i++) {
Character c = str.charAt(i);
if (c == 'a'
|| c == 'A'
|| c == 'e'
|| c == 'E'
|| c == 'i'
|| c == 'I'
|| c == 'o'
|| c == 'O'
|| c == 'u'
|| c == 'U') {
if (vowels.containsKey(c)) {
vowels.put(c, vowels.get(c) + 1);
} else {
vowels.put(c, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : vowels.entrySet()) {
System.out.print(entry.getKey() + "=" + entry.getValue() + " ");
}
}}
Input : charActer
Output : a=1 A=1 e=1

Write method countVowels to take a string and return the amount of vowels

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Input the string: ");
String str = in.nextLine();
System.out.print("Number of Vowels in the string: " + countVowels(str)+"\n");
}
public String countVowels(String count) {
}
sorry but im very new to java and coding and trying to find a way to create a vowel counter but I seem to struggle with creating one ive tried looking up many answers but cant find one.
Try something like this:
public int countVowels(String str)
{
int vowelCount = 0;
for (int i = 0; i < str.length(); i++)
{
if (str.toLowerCase().toCharArray()[i] == 'a' | str.toLowerCase().toCharArray()[i] == 'e' | str.toLowerCase().toCharArray()[i] == 'i' | str.toLowerCase().toCharArray()[i] == 'o' | str.toLowerCase().toCharArray()[i] == 'u')
{
vowelCount++;
}
}
return vowelCount;
}
and if you want to include 'y', just add another comparison to the if statement
public static String countVowels(String count) {
int Vowelcount = 0;
String[] arr = count.split(" ");
//looping through string array
for (int i = 0; i <= arr.length - 1; i++) {
//looping through each character in the next element
for (char ch : arr[i].toCharArray()) {
//checking if ch == to vowels
if (ch == 'e' || ch == 'a' || ch == 'o' || ch == 'u' || ch == 'i') {
//add counts number of vowels for every string array index
Vowelcount += 1;
}
}
}
return Integer.toString(Vowelcount);
}
This should work just fine... I've split your words in the input string into a string array.

Counting characters from a user inputted string of more than one word

I'm trying to create a program where the user inputs a word and then the program displays every letter of the alphabet with a number next to it that shows how many times that letter was used in the word. It works great, but the only problem is that it only works with one word strings. How can I add detection for strings of more than one word? Thanks in advance.
My code:
import java.util.Scanner;
public class LetterOccurrenceCount {
public static void main(String[] args) {
// TODO Auto-generated method stub
int array[] = new int[26];
for (int i = 0; i < array.length; i++)
{
array[i] = 0;
}
Scanner Keyboard = new Scanner(System.in);
String userInput;
System.out.println("Please enter a string.");
userInput = Keyboard.next().toLowerCase();
for (int i = 0; i < userInput.length(); i++)
{
char ch = userInput.charAt(i);
if (ch >= 'a' && ch <= 'z') {
array[ch - 'a'] ++;
}
}
for (char ch='a'; ch<='z'; ++ch) {
System.out.print(ch + " = " + array[ch-'a'] + " | ");
}
}
}

Output the word in a string with the largest amount of vowels

I mostly have the method done but I am confused when it comes to the If statement concerned with storing a variable with the word with the most amount of vowels, NOTE I am not allowed to use arrays.
below is my code
//method for vowels and consonants
public static int Vowelcount(String sentence)
{
int maxvowelcount =0;
int minvowelcount =0;
String vowel="";
int consonantcount = 0;
int vowelcount = 0;
int index = 0;
String currentword;
int spacePos;
int noOfchars = 0;
int largest = 0 ;
int smallest = 0 ;
//gets rid of leading and trailing spaces so as to get the last word
sentence=sentence.trim() + " ";
//assignments
spacePos=sentence.indexOf(" ");
currentword = sentence.substring(0, spacePos);
while (spacePos >-1)// when no spaces are found
{
noOfchars=0;
currentword = sentence.substring(0, spacePos);
// remove the first word
sentence = sentence.substring(spacePos+1);
spacePos=sentence.indexOf(" ");
// to count the number of vowels in the string
for(index = 0; index<currentword.length(); index++)
{
if(currentword.charAt(index)=='a' || currentword.charAt(index)=='e' ||
currentword.charAt(index)=='i' || currentword.charAt(index)=='o' ||
currentword.charAt(index)=='A' || currentword.charAt(index) == 'E' ||
currentword.charAt(index) == 'I' || currentword.charAt(index) == 'O' )
{
vowelcount++;
}
else
{
consonantcount++;
}
//if statement to overwrite currentword with largest/smallest
if (index == 0)
{
minvowelcount = currentword.length();
maxvowelcount = currentword.length();
}
if (vowelcount < minvowelcount)
{
minvowelcount = vowelcount;
}
if (vowelcount > maxvowelcount)
{
maxvowelcount = vowelcount;
vowel=currentword;
}
}
}
//output to show the word with largest amount of vowels
System.out.println( "word with largest amount of vowels is " + vowel);
return vowelcount;
}
First, many of the variables you use are redundant. All you need is the max number of vowels and the word.
Next point is that all your if statements should be outside the for loop. The general structure must be smth like
wordWithMaxVowels = "";
maxVowels = 0;
while (there is a word) {
fetch the word
vowelCount = 0;
for (every char in the word)
{
if (char is vowel)
vowelCount++;
}
if (vowelCount > maxVowels)
{
vowelCount = maxVowels;
wordWithMaxVowels = word;
}
}
// here maxVowels is the maximal number of vowels in a word, wordWithMaxVowels is the word itself;
Also note, that it's not any optimal to chop off the first word in the sentence. Try the following:
int wordStart = 0;
int wordEnd;
while(true) {
wordEnd = sentence.indexOf(" ", wordStart);
if (wordEnd < 0)
break;
String word = sentence.substring(wordStart, wordEnd);
// process the word
wordStart = wordEnd + 1;
}

Hangman wrong guesses not printing correctly

I have this Hangman program that i am working on for school and i cant get the number of wrong guesses to print correctly when the user guesses a wrong letter. Here is my code that i got so far, i would appreciate any tips.
import java.util.Scanner;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
char[] wordChars = word.toCharArray();
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
In this loop, you increment rightGuesses by 1 every time the guess matches a letter in the word, and wrongGueeses by 1 every time the guess does not match a letter in the word. As you can imagine, this will lead to the numbers, collectively, being incremented by the same number as the number of letters, when it should only be incremented once.
Try something like:
boolean foundMatch = false;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
if (!foundMatch)
{
++rightGuesses;
foundMatch = true;
}
}
}
if (!foundMatch)
{
++wrongGuesses;
}
// end of for loop
Now we only increment one of rightGuesses and wrongGuesses once - rightGuesses can only be incremented if we have not found a match (setting found match to true), and wrongGuesses can only be incremented once if we have not found a match.
problem is in your for loop. You are iterating over each letter, and for every letter that doesn't match yours, you mark it as an incorrect guess. It should only be marked incorrect if NONE of the letters are correct. Additionally it should only be marked right if you haven't marked it already.
import java.util.Scanner;
import java.util.ArrayList;
public class HangmanTest {
public static void main(String[] args) {
String[] wordBank = { "madelynn", "crystal", "mcbride", "daughter",
"adorable", "beautiful", "andrew", "programming", "alyssa",
"computers", "mcbreezy", "maddy", "happy", "vacation", "beach",
"java", "benefical", "military", "veteran", "standale",
"lions", "tigers", "redwings", "pistons", "michigan",
"football", "baseball", "hockey", "basketball", "golf" };
int minimum = 0;
int maximum = wordBank.length - 1;
String again;
do {
int choice = minimum + (int) (Math.random() * maximum);
String word = wordBank[choice];
// Converts the random word to asterix
String userWord = "";
for (int i = 0; i < word.length(); i++) {
userWord += "*";
}
String guessedLetters="";
// Breaks into a bunch of characters
char[] userWordCh = userWord.toCharArray();
// Show the random word
System.out.println("The word for you to guess is " + userWord);
// instantiate a scanner object
Scanner input = new Scanner(System.in);
int size = word.length();
int rightGuesses = 0;
int wrongGuesses = 0;
boolean foundLetter;
char[] wordChars = word.toCharArray();
guessLoop:
while (size != rightGuesses) {
System.out.println("Enter a character: ");
String response = input.next();
char ch = response.charAt(0);
foundLetter=false;
for (int i=0;i<guessedLetters.size();i++){
if (ch == guessedLetters.charAt(i)){
System.out.println("Already guessed that letter!");
continue guessLoop;
}
}
guessedLetters+=response;
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
foundLetter=true;
userWordCh[i] = ch;
++rightGuesses;
}
} // end of for loop
if(!foundLetter)
++wrongGuesses;
System.out.print("The word is: ");
for (int j = 0; j < userWordCh.length; j++)
System.out.print(userWordCh[j]);
System.out.println();
} // end of while loop
System.out.println("You had " + wrongGuesses + " wrong guesses.");
System.out.println("Would you like to play again y/n: ");
again = input.next();
} while (again.equals("y"));
}
}
I'm guessing here, but I think this might be wrong:
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
This will increment the rightGuesses and wrongGuesses variables for each character in the word that matches/doesn't match the inputted character. Instead, you need to set a flag when a character "matches", then check that flag at the end to update rightGuesses and wrongGuesses.
for (int i = 0; i < word.length(); i++) {
if (wordChars[i] == ch) {
userWordCh[i] = ch;
++rightGuesses;
} else {
++wrongGuesses;
}
} // end of for loop
This for loop is causing your problem with wrong guesses, since it will say that a character is a wrong guess even though it is in the word. An option you can do is have some boolean that is switched to true when it finds the letter. That way, when you leave the for loop, you check to see if that value is true. If it isn't, increment the wrong guesses.

Categories