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);
}
}
Related
The following is my code for converting all the words of the sentence into PigLatin, ie "Her food is stolen" to "ERHAY OODFAY ISAY OLENSTAY", but the output which I am getting is ERHAY. Any corrections would be appreciated. Thanks.
public class piglatin
{
public void main(String s)
{
s=s.toUpperCase();
s=s+" ";
int l=s.length();
String word="";
int n=0;
int w=0;//no of words in s(loop1)
int wor=0;//no of words loop2
for(int i=0;i<l;i++)
{char c=s.charAt(i);
if(c==' ')
w++;
}
for(int i=0;i<l;i++)
{ char c=s.charAt(i);
int m=s.indexOf(' '); //length of first word
if(i==0)
{ for(int j=0;j<m;j++)
{char c1=s.charAt(j);
if(c1=='A'||c1=='E'||c1=='I'||c1=='O'||c1=='U')
{n=j;//index of first vowel
j=m;}
}
word=s.substring(n,m)+s.substring(0,n);
System.out.print(word+"AY"+" ");
}
if(c==' '&&wor!=w-1)
{ s=s.substring(m+1,l);
l=s.length();
i=0;
wor++;
}
if(wor==w-1)
i=l+1;
}
}
}
You can simplify it greatly by splitting the sentence on whitespace and processing each word of the resulting array.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = scanner.nextLine();
s = s.toUpperCase();
String[] words = s.split("\\s+");// Split s on whitespace
// Process each word from words[]
for (String word : words) {
int m = word.length(), j;
for (j = 0; j < word.length(); j++) {
char c1 = word.charAt(j);
if (c1 == 'A' || c1 == 'E' || c1 == 'I' || c1 == 'O' || c1 == 'U') {
break;
}
}
String translated = word.substring(j, m) + word.substring(0, j);
System.out.print(translated + "AY" + " ");
}
}
}
A sample run:
Enter a sentence: Her food is stolen
ERHAY OODFAY ISAY OLENSTAY
Alternatively, in addition to using String#indexOf(int ch), you can use String#indexOf(String str, int fromIndex) to get all the words of the sentence.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = scanner.nextLine();
s = s.toUpperCase();
// Start from index, 0
int fromIndex = 0, lastPositionOfWhitespace = -1;
for (int i = 0; i < s.length(); i++) {
int indexOfWhitespace = s.indexOf(' ', fromIndex);
String word = "";
if (indexOfWhitespace != -1) {
lastPositionOfWhitespace = indexOfWhitespace;
word = s.substring(fromIndex, indexOfWhitespace);
fromIndex = indexOfWhitespace + 1;
} else {
word = s.substring(lastPositionOfWhitespace + 1);// Last word of the sentence
i = s.length();// To stop further processing of the loop with counter, i
}
int m = word.length(), j;
for (j = 0; j < word.length(); j++) {
char c1 = word.charAt(j);
if (c1 == 'A' || c1 == 'E' || c1 == 'I' || c1 == 'O' || c1 == 'U') {
break;
}
}
String translated = word.substring(j, m) + word.substring(0, j);
System.out.print(translated + "AY" + " ");
}
}
}
A sample run:
Enter a sentence: Her food is stolen
ERHAY OODFAY ISAY OLENSTAY
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
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.
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);
}
}
Here's my attempt to write this code but I'm getting lost with a main part.I'm not sure how the loop will know when a new word starts.For now I know only loops and if-else statements.I would really appreciate if you could just push me in a right direction because this problem is way too hard for me.
Rules of pig latin:
1)If a word begins with a vowel,add a dash and "way" to the end.
2)Otherwise,add a dash,move the first letter to the end,and add "ay"
/*Enter a line of text: This is a test.
Input: this is a test.
Output: his-tay is-way a-way est-tay.
*/
import java.util.Scanner;
public class PigLatin
{
public static void main(String[]args)
{
int count;
String input;
char empty = ' ',first;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
input = keyboard.nextLine();
System.out.println();
for(count = 0; count < input.length(); count++)
if(input.charAt(0) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(count + 1) + "-" + input.charAt(0) + "ay");
else if(input.charAt(count) == empty)
first = input.charAt(count + 1)
if(input.charAt(first) != 'a' || input.charAt(0) != 'e' != input.charAt(0) != 'o' != input.charAt(0) != 'i' != input.charAt(0) != 'u')
System.out.print(input.charAt(first + 1) + "-" + input.charAt(first) + "ay");
else if()
System.out.print("-way"); //I'm lost here.
}
}
Try the following:
import java.util.Scanner;
public class PigLatin {
static final char vowelRegex = "^[aeiouy]"; //Is y a vowel?
public static void main(String[]args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String input = keyboard.nextLine();
String[] words = input.split(' ');
for(int i=0; i<words.length; i++) {
if(words[i].matches(vowelRegex)) {
System.out.print(words[i] + "-way ");
} else {
System.out.println(words[i].substring(1) + words[i].charAt(0) + "-ay ";
}
}
}
}