Counting Vowels, Repetition method - java

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);
}
}

Related

print the word which has maximum number of vowel in java

I want to print the word which is containing maximum number of vowel. But Problem is that last word of sentence which is containing maximum number is not print. please help me solve that problem. My code is below.
When i enter input 'Happy New Year', Output is 'Yea' .But i want i output is 'Year'
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter The Word : ");
String sentence = sc.nextLine();
String word = "";
String wordMostVowel = "";
int temp = 0;
int vowelCount = 0;
char ch;
for (int i = 0; i < sentence.length(); i++) {
ch = sentence.charAt(i);
if (ch != ' ' && i != (sentence.length() - 1)) {
word += ch;
ch = Character.toLowerCase(ch);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
} else {
if (vowelCount > temp) {
temp = vowelCount;
wordMostVowel = word;
}
word = "";
vowelCount = 0;
}
}
System.out.println("The word with the most vowels (" + temp + ") is: " + " " + wordMostVowel);
}
}
You cut words at spaces (correct), but you also cut at the last character, even if it's not a space (so this character is never dealt with). And that's not correct.
Here is a possibility:
import java.util.Scanner;
public class Abcd {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the sentence : ");
String sentence = sc.nextLine();
String wordMostVowels = "";
int maxVowelCount = 0;
for (String word : sentence.split(" ")) {
int vowelCount = 0;
for (char c : word.toLowerCase().toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
vowelCount++;
}
}
if (vowelCount > maxVowelCount) {
maxVowelCount = vowelCount;
wordMostVowels = word;
}
}
System.out.println("The word with the most vowels (" + maxVowelCount + ") is: " + wordMostVowels);
}
}

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.

Java Why do I get this error? Exception in thread "main" java.lang.NullPointerException

This is the code that it is giving me the error for on the line with >>>>>>> I've already looked at this thread Exceptions but I still do not understand what I need to change :( I am a total beginner to programming.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class manyVowels {
public static final String wordList = "words.txt";
public static void main(String[] args) {
Scanner fileIn = null;
try {
//locate and open file
fileIn = new Scanner(new FileInputStream("words.txt"));
} catch (FileNotFoundException e) {
//if the file cannot be found, the program prints the message and quits
System.out.println("File not found. ");
System.exit(0);
}
String word = null;
if (fileIn.hasNext()) //if there is another word continue
{
String finalWord = null; // defines the word with most consecutive vowels
int maxVowels = 0;//sets initial value to 0
while (fileIn.hasNext()) {
// for each word in the file
int vowels = 0;
/*error here-->*/ for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
// for each character in the word, and exit early if the word is not long enough to beat maxVowels
if (hasVowels(word.charAt(i))) {
// consonants reset this to 0
vowels++;
} else {
// reached the end of the word so check if the count is higher than maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
vowels = 0;
}
}
// comparing vowels to maxVowels
if (vowels > maxVowels) {
maxVowels = vowels;
finalWord = word;
}
}
//seek vowels
word = fileIn.next();
for (int i = 0; i < word.length(); i++) {
if
((word.charAt(i) == 'A')
|| (word.charAt(i) == 'E')
|| (word.charAt(i) == 'I')
|| (word.charAt(i) == 'O')
|| (word.charAt(i) == 'U')
|| (word.charAt(i) == 'a')
|| (word.charAt(i) == 'e')
|| (word.charAt(i) == 'i')
|| (word.charAt(i) == 'o')
|| (word.charAt(i) == 'u')) {
//prints the final word with the most consecutive vowels
System.out.println("The word with the most consecutive vowels is: " + word);
System.exit(0);
}
}
}
}
private static boolean hasVowels(char charAt) {
throw new UnsupportedOperationException("Inserted by template."); //NetBeans generated method
}
}
Following the logic, you initialize the String word to null, and then proceed to call word.length().
word, being null, has no length(). Thus, the NullPointerException.
Assign a string to word before attempting to measure its length.
String word = "Hello!";
The variable word seems to be null, I think you skipped an instruction in which you fill it with a word read from fileIn. Your code should read something like this:
while (fileIn.hasNext()) {
// for each word in the file
word = fileIn.next();
int vowels = 0;
for (int i = 0; i < word.length() && i < word.length() - maxVowels + vowels; i++) {
...
you defined word as a null. When you say word.length() it means you are saying
null.length() that's why you are getting null pointer exception.
You should initialize String variable "word" before doing any operation( calling any string method by using '.' )
If you have any predefined value, initialize with that else initialize with empty string.
String word = "xyz" ;
String word = "" ;

Taking vowels from string. Java

I'm having trouble with this simple exercise. What I have to do is to take the vowels from the string.
This returns all the vowels in the string, but what I want is that if there are multiple letters of same vowel, just return one.For example, using the string "aaa eee iii" should give "a e i".
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u')) {
aChar = aString.charAt(i);
System.out.print(aChar + " ");
}
}
}
I would recommend either adding each vowel found to a HashSet<Character>, or calling aString.contains() with each vowel in turn. You can also use aString.toLowerCase() so that you only have to check for lowercase vowels.
Edit your code as follows:
public static void getVowels(char aChar, String aString)
{
System.out.print("Your string has the following vowels: ");
String vowels="";
for (int i = 0; i < aString.length(); i++)
{
if ((aString.charAt(i) == 'a') || (aString.charAt(i) == 'e') || (aString.charAt(i) == 'i') || (aString.charAt(i) == 'o') || (aString.charAt(i) == 'u'))
{
if(!vowels.contains(String.valueOf(aString.charAt(i))))
vowels+=aString.charAt(i);
}
}
for(int i=0;i<vowels.length();i++)
System.out.print(vowels.charAt(i)+" ");
}
EDIT :
Alternatively,
public static void getVowels(char aChar, String aString){
System.out.print("Your string has the following vowels: ");
char vowels[]={'a','e','e','o','u'};
for (char vowel : vowels)
{
if(aString.indexOf(vowel)>=0)
{
System.out.print(vowel+" ");
}
}
}
Why are you doing for loop? Just check String.IndexOf() and if that character is present print it.
You need to have a string where you keep on adding unique vowels checking before hand whether it exists. The below program will clear your doubt.
public class TestWovel {
public static void main(String[] args) {
String vowel = "aaaeeeiiizncnzcxjswdmmnmxcuuooo";
String uniqueVowels = "";
for(int i=0;i<vowel.length();i++){
char vowelFound = vowel.charAt(i);
if((vowelFound == 'a' || vowelFound == 'e' || vowelFound == 'i' || vowelFound == 'o' || vowelFound == 'u') && (uniqueVowels.indexOf(vowelFound) == -1)){
uniqueVowels+=vowelFound;
}
}
System.out.println(uniqueVowels);
}
}
You could use an integer array whose indexes are ASCII codes. When you see a vowel, check its count in the array. If the count is 0, print the vowel and increase the count. For example, 'a' would be stored in arr[97]:
public static void getVowels(String aString) {
int[] arr = new int[128];
char c;
System.out.print("Your string has the following vowels: ");
for (int i = 0; i < aString.length(); i++){
c = aString.charAt(i);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
if (arr[c] == 0) {
System.out.print(aString.charAt(i) + " ");
arr[c]++;
}
}
}
}

Categories