Java count the vowels program [closed] - java

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to make a program that lets the user input a word, then it will count the number of vowels and consonants in that word and print the amount. e.g: The word 'YOURWORD' contains 3 vowels and 5 consonants.
Since a consonant is just each letter that isn't a vowel, I only made the program check if there was a vowel in the word and then the number of consonants is just the number of other letters in the word. However, I'm struggling with the for loop. Here is my code:
String word;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
char[] wordc = word.toCharArray();
for(int w = 0;w > word.length();w++;) {
if(wordc[w] == 'a' || wordc[w] == 'e' || wordc[w] == 'i' || wordc[w] == 'o' || wordc[w] == 'u') {
}
As you can see, I'm so close to the end but I literally have no clue what to do now. I'm a beginner at Java and I have checked the for loop syntax but I really don't know what to do, please help.

Try changing
for(int w = 0;w > word.length();w++)
to
for(int w = 0;w < word.length();w++)
because when you set w to 0, obviously, your word.length() is greater than 0, which makes the condition in the for loop false. Hence, the for loop would be not be executed even once.
To count the number of vowels, you define one more integer outside the for loop and increment it as you encounter a vowel. So, your code should look like:
String word;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
//Convert your string to lowercase using toLowerCase() method.
char[] wordc = word.toLowerCase().toCharArray();
int vowels = 0; //This counter will count the vowels.
for(int w = 0;w < word.length();w++) {
if(wordc[w] == 'a' || wordc[w] == 'e' || wordc[w] == 'i' || wordc[w] == 'o' || wordc[w] == 'u') {
vowels++;
}
}
int consonants = word.length() - vowels;
//Assuming no special characters in your word.

You should define two int variables to do counting.
the for loop goes like below
String word;
int numberOfVowls = 0; numberofCosonents = 0;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
char[] wordc = word.toCharArray();
for(int w = 0;w < word.length();w++;) {
if(wordc[w] == 'a' || wordc[w] == 'e' || wordc[w] == 'i' || wordc[w] == 'o' || wordc[w] == 'u') numberOfVowls++;
else numberofCosonents++;}

String word;
Scanner myinput = new Scanner(System.in);
System.out.println("Please enter a word.");
word = myinput.next();
char[] wordc = word.toCharArray();
int vowels = 0;
for (char w: wordc) {
if(w == 'a' || w == 'e' || w == 'i' || w == 'o' || w == 'u') {
vowels++;
}
}
System.out.println("Number of vowels in " + word + " is: " + vowels);
System.out.println("Number of consonants in " + word + " is: " + (wordc.length - vowels));

Here is a way to count vowels and consonants without using loops and multiple conditions.
String word = "YOURWORD"; // assuming only letters
String vowels = word.replaceAll( "(?i)[^aeiou]+", "" ); // OUO
int numVowels = vowels.length(); // 3
int numConsonants = word.length() - numVowels; // 5
How it works:
In the word.replaceAll( "(?i)[^aeiou]+", "" ) call we are replacing everything that is not one of [^aeiou] thus leaving only vowels in returned string.

String[] arr = text.split(" ");
char elementch = ' ';
//looping through string array
for(int i=1; i<= arr.length ; i++){
String nextElement = arr[i-1];
int add = 0;
//looping through each character in the next element
for (char ch: nextElement.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
add = add +1;
elementch = ch;
System.out.print(" ' " +elementch + " ' ");
}else{
//do nothing
}
}
System.out.println("The number of vowels is "+ add + " in" + " : " + nextElement.toUpperCase());
}

Related

I want to print the number of vowels, consonants, spaces, digits and special characters in the string entered by user [duplicate]

This question already has answers here:
StringIndexOutOfBoundsException in a counting loop in Java
(3 answers)
Closed 2 years ago.
I need to print no. of vowels, consonants, spaces, digits and special characters in the string entered by user.
I am getting below error after running the program.
Input: Enter the word to count Vowels and Alphabets in it
java language version 15#
Output:
java.lang.StringIndexOutOfBoundsException: String index out of range: 25
at java.lang.String.charAt(String.java:658)
at CountAlphabetsInWord.main(CountAlphabetsInWord.java:11)
public class CountAlphabetsInWord {
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the word to count Vowels and Alphabets in it");
String word = scanner.nextLine();
scanner.close();
int vowels = 0, consonants = 0, spaces = 0, digits = 0, specialCharacters = 0;
word = word.toLowerCase();
for(int i = 0; i <= word.length(); i++){
char ch = word.charAt(i);
//check if any char is a, e, i, o ,u
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u'){
vowels++;
}
else if(ch >= '0' && ch <= '9'){
consonants++;
}
else if(ch == ' '){
spaces++;
}
else if(ch >= 'a' && ch <= 'z'){
digits++;
}
else
specialCharacters++;
}
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Digits: " + digits);
System.out.println("WhiteSpaces: " + spaces);
System.out.println("Special Characters: " + specialCharacters);
}
} ```
Consider using an enhanced for loop so you don't have to worry about index out of bound errors, and for similar reasons utilize the inbuilt Character methods:
import java.util.Scanner;
import java.util.Set;
public class AnalyzeStringInput {
private static final Set<Character> VOWELS = Set.of('a', 'e', 'i', 'o', 'u');
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a string:");
String string = scanner.nextLine();
int vowels = 0, consonants = 0, spaces = 0, digits = 0, specialCharacters = 0;
for (Character ch : string.toLowerCase().toCharArray()) {
if (Character.isLetter(ch)) {
if (VOWELS.contains(ch)) {
vowels++;
} else {
consonants++;
}
} else if (Character.isSpaceChar(ch)) {
spaces++;
} else if (Character.isDigit(ch)) {
digits++;
} else {
specialCharacters++;
}
}
System.out.println();
System.out.println("Vowels: " + vowels);
System.out.println("Consonants: " + consonants);
System.out.println("Spaces: " + spaces);
System.out.println("Digits: " + digits);
System.out.println("Special Characters (anything else): " + specialCharacters);
}
}
Example Usage:
Please enter a string:
AbcDeF gHi JkLmnO 1234% ~!56&*()
Vowels: 4
Consonants: 11
Spaces: 5
Digits: 6
Special Characters (anything else): 7
The index word.length() is beyond the range of characters in word. Remember, it’s zero-indexed, so the range of characters is 0 to word.length - 1.
You just need to tweak your for-loop:
for(int i = 0; i < word.length(); i++){
use "i<word.length()" in for loop

How do I count number of spaces, vowels, and characters?

import java.util.*;
import java.lang.String;
public class counter
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int space = 0,vowel = 0,chara = 0,i;
System.out.println(" Enter String ");
String s =in.nextLine();
for( i = 0; i < s.length(); i++)
{
char ch = in.next().charAt(i);
if(ch == ' ')
space++;
if(ch == 'e' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowel++;
else
chara++;
System.out.println("Number of Vowels = "+vowel);
System.out.println("Number of Spaces = "+space);
System.out.println("Number of Char = "+chara);
}
}
}
What is the problem? I have put three counters to count. I am coding in Eclipse and whenever I check the console I am not able to count the characters. It is just accepting inputs and not doing anything else.
Remove char ch = in.next().charAt(i);, and replace the other instances of ch with s.charAt(i)
The first charAt check should also be a, you have e twice.
Then move System.out.println... outside of the loop.
Online Demo
Just a couple of typo errors. Change your code with,
String s = in.nextLine().toLowerCase();
And
char ch = s.charAt(i);
And
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
In your code you are using lowercase letters to compare with the user input. So you should convert the user input to lower case first. Your current code ignores all uppercase vowels(E, A, I ...). Use toLowerCase().
By using in.next() the Scanner is waiting for an input. Since you have already taken an input using nextLine() you can use that.
Next one is obviously a typographical error. Vowels are A, E, I, O, U.
You should change s = in.next().charAt(i);to String s =in.nextLine() and put System.out.printlnpart outside of for loop.
Also there is double 'e' (with the help of #Ted Hopp):
ch == 'e' || ch == 'e' to ch == 'e' || ch == 'a'
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int space = 0,vowel = 0,chara = 0,i;
System.out.println(" Enter String ");
String s =in.nextLine();
for( i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if(ch == ' ')
space++;
if(ch == 'e' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
vowel++;
else
chara++;
}
System.out.println("Number of Vowels = "+vowel);
System.out.println("Number of Spaces = "+space);
System.out.println("Number of Char = "+chara);
}

How can I search for a character in strings without using a loop?

My assignment is: if the user-inputted word has no vowels, then "ay" is added to the end, if it starts with a vowel then it adds "yay" to the end, otherwise if it doesn't meet any of these conditions then the first letter gets moved to the end of the word and "ay" is added to the end. I can't seem to get the last condition to work. For example the word "sad" should output "adsay" but instead it outputs "saday" which means that it is reading and accepting another if statement. I've tried to look up some solutions but all I've gotten are loops and I'd like to avoid loops for this particular assignment. Here is my code:
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Word: ");
String word = in.nextLine();
int length = word.length();
String word1 = "";
if (word.charAt(0) == 'a' || word.charAt(0) == 'e' || word.charAt(0) == 'i' || word.charAt(0) == 'o' || word.charAt(0) == 'u')
{
word1 = pigLatin(word);
System.out.println("Pig Latin: " + word1);
}
else if (word.indexOf("a") == -1 || word.indexOf("e") == -1 || word.indexOf("i") == -1 || word.indexOf("o") == -1 || word.indexOf("u") == -1)
{
word1 = pigLatin1(word);
System.out.println("Pig Latin: " + word1);
}
else
{
word1 = pigLatin2(word);
System.out.println("Pig Latin: " + word1);
}
}
static String pigLatin(String word)
{
String x = word + "yay";
return x;
}
static String pigLatin1(String word)
{
String x = word + "ay";
return x;
}
static String pigLatin2(String word)
{
char firstLetter = word.charAt(0);
String x = word.substring(1, word.length()) + firstLetter + "ay";
return x;
}
}
The problem lies in your second if statement:
else if (word.indexOf("a") == -1 || word.indexOf("e") == -1 || word.indexOf("i") == -1 || word.indexOf("o") == -1 || word.indexOf("u") == -1)
{
word1 = pigLatin1(word);
System.out.println("Pig Latin: " + word1);
}
Because you're using "or" here (the || operator), your program will enter this block as long as the word doesn't contain "a", or doesn't contain "e", etc. For your test input, "sad" contains "a" but it doesn't contain "e"... so you wind up calling pigLatin1("sad").
Change this if to use "and" instead (the && operator). That way, the word will need to not have every defined vowel, instead of not having at least one defined vowel.
else if (word.indexOf("a") == -1 && word.indexOf("e") == -1 && word.indexOf("i") == -1 && word.indexOf("o") == -1 && word.indexOf("u") == -1)

Trying to end loop when user input = q

Essentially I am trying to create a Pig Latin converter. However, for this assignment a requirement is to allow the user to enter 'Q' to quit entering in words. I can get the code to compile, but whenever the user enters Q it crashes and throws:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:658)
at mission4aa.Mission4AA.main(Mission4AA.java:38)
I am just completley unsure where to even go about fixing this. I've been trying.
import java.util.Scanner;
public class Mission4AA {
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
System.out.println("Enter another word(Q to exit): ");
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}
}
Because when you are doing this check
if(userInput.charAt(1) != firstVowel) {
If the user has input a 'q', userInput will only have a 0 term ( Length 1 ). You are effectively trying to get the second character of the users input. To solve your problem, i would do the check for 'q' at the start of the do section ( or simply scrap the do-while concept and use a while(true) loop ). Note that in future you should handle input that is of length 1. But for your issue, something like this would work
do {
userInput = scanIn.next();
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
//here
if(userInput.equals("q") || userInput.equals("Q")){
System.out.println("Thank you");
return;
}
//else continue
If the user enters just Q or q - there's no char at index 1, which is why your code throws the java.lang.StringIndexOutOfBoundsException exception.
There are many ways to fix this. In my case, I just converted your do-while to a while(true) and I use break if the input is just Q or q.
// get first input
userInput = scanIn.next();
while(true){
userInput = userInput.trim();
userInput = userInput.toLowerCase();
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
}
}
// check next word here - if Q or q, break out and finish
userInput = scanIn.next();
if(userInput.equalsIgnoreCase("q")) {
break;
}
System.out.println("Enter another word(Q to exit): ");
}
Note - you'd need to rearrange your print statements accordingly.
The problem appears to be that you read the user input in the beginning of the loop, thus the condition in your do-while loop checks the previous user input - not the new one.
In addition the else-branch of your if-statement assumes that the input is at least 2 characters long if(userInput.charAt(1) != firstVowel) {...}.
This is what causes the exception as the input "q" reaches the else-branch, but is only of length 1.
You need to make two changes to your code:
You need to read the userinput before checking the loop-condition.
In the else-branch you must check that the input is at least 2 characters long before checking if the second character is a vowel.
Modified code below:
public static void main(String[] args) {
Scanner scanIn = new Scanner(System.in);
String userInput;
int firstVowel = 0;
System.out.println("Welcome to the pig latin translator!");
System.out.println("Please enter a word (Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
do {
int end = userInput.length();
char a = userInput.charAt(0);
if (a == 'a' || a == 'e' || a == 'i' || a == 'o' || a == 'u' )
System.out.println(userInput + "way");
else { //Check for next vowel if the first letter is consonant
for (int i = 1; i < userInput.length(); i++) {
char b = userInput.toLowerCase().charAt(i);
if (b == 'a' || b == 'e' || b == 'i' || b == 'o' || b == 'u' ) {
firstVowel = i; //Stores the index of the first vowel
break;
}
}
if(end > 1 && userInput.charAt(1) != firstVowel) {
String startString = userInput.substring(firstVowel, end);
String endString = userInput.substring(0, firstVowel) + "ay";
String result = startString + endString;
System.out.println("Translation: " + result);
} else { /* Handle handle input of length 1 */}
}
System.out.println("Enter another word(Q to exit): ");
userInput = scanIn.next().trim().toLowerCase();
} while (!userInput.equalsIgnoreCase("q"));
System.out.println("Thank you");
}

Counting Vowels, Repetition method

public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int countVowel=0;
int countVowelA=0;
int countVowelE=0;
int countVowelI=0;
int countVowelO=0;
int countVowelU=0;
char ch;
String str;
System.out.println("Please enter the string : ");
str = sc.nextLine();
for(int i = 0; i<=str.length(); i ++)
{
ch = str.charAt(i);
if(ch == 'a' || ch =='A')
{
countVowelA++;
countVowel++;
}
if(ch == 'e' || ch =='E')
{
countVowelE++;
countVowel++;
}
if(ch == 'i' || ch =='I')
{
countVowelI++;
countVowel++;
}
if(ch == 'o' || ch =='O')
{
countVowelO++;
countVowel++;
}
if(ch == 'u' || ch =='U')
{
countVowelU++;
countVowel++;
}
i++;
}
System.out.println("Occurances of A in given string : " +countVowelA);
System.out.println("Occurances of E in given string : " +countVowelE);
System.out.println("Occurances of I in given string : " +countVowelI);
System.out.println("Occurances of O in given string : " +countVowelO);
System.out.println("Occurances of U in given string : " +countVowelU);
System.out.println("Number of vowels in strings are : " +countVowel);
}
}
For me i am having trouble, let's say for example if i type lebron james is the best basketball player, u know it. It gives me an error and also it doesn't count all the vowels? Also, can u tell if my code is right
check line below
for(int i = 0; i<=str.length(); i ++)
change to
for(int i = 0; i<str.length(); i ++)
why?
Because in Java, index start from zero. When you have i <= str.length, it goes beyond scope index of string and gives you java.lang.StringIndexOutOfBoundsException
Another issue, You have incremented variable i twice. Second after if clauses is totally unnecessary because it gives you wrong answer even if you rectify the boundary issue.
Your loop variable i, as was mentioned in the comments, is incremented twice. Once in the for statement itself, and the other at the end of the loop.
This means that the counter goes: 0,2,4,6 instead of 0,1,2,3.
That will give you the wrong answer.
However, the reason for the error is not this, but the fact that you check the condition until i <= str.length(), instead of i < str.length(). The characters in a string with, say, 3 characters like "the" are 0,1,2. There is no character number 3. So when i is equal to str.length, you get an error.
Try this code
import java.util.Scanner;
public class CountVowels {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int countVowel=0;
int countVowelA=0;
int countVowelE=0;
int countVowelI=0;
int countVowelO=0;
int countVowelU=0;
char ch;
String str;
System.out.println("Please enter the string : ");
str = sc.nextLine();
char[] c = str.toCharArray();
for(int i = 0; i<c.length; i ++)
{
if(c[i] == 'a' || c[i] =='A')
{
countVowelA++;
countVowel++;
}
else if(c[i] == 'e' || c[i] =='E')
{
countVowelE++;
countVowel++;
}
else if(c[i] == 'i' || c[i] =='I')
{
countVowelI++;
countVowel++;
}
else if(c[i] == 'o' || c[i] =='O')
{
countVowelO++;
countVowel++;
}
else if(c[i] == 'u' || c[i] =='U')
{
countVowelU++;
countVowel++;
}
//i++;
}
System.out.println("Occurances of A in given string : " +countVowelA);
System.out.println("Occurances of E in given string : " +countVowelE);
System.out.println("Occurances of I in given string : " +countVowelI);
System.out.println("Occurances of O in given string : " +countVowelO);
System.out.println("Occurances of U in given string : " +countVowelU);
System.out.println("Number of vowels in strings are : " +countVowel);
}
}

Categories