I'm attempting to create a case that identifies every use of 'E' or 'e' in a string but am unsure how to format it correctly.
I've attempted separating 'E' and 'e' as seperate variables but this doesn't seem to work
The output should tell the user how many uses of 'e' or 'E' are in the string they entered, but I am just getting formatting errors. Additionally, if I limit it to either just 'e' or 'E' the program is able to work, however, I get a long string of numbers from it being counted in my for loop, is there any way to just display the final number from my for loop?
case 3: String phrase;
phrase = scan.nextLine();
System.out.println("What is your sentence");
phrase = scan.nextLine();
int numOfE = 0;
for (int i = 0; i < phrase.length(); i++) {
if (phrase.charAt(i) == 'e' or == 'E') {
numOfE++;
}
System.out.println(numOfE);
}
Change:
if (phrase.charAt(i) == 'e' or == 'E')
to
if (phrase.charAt(i) == 'e' || phrase.charAt(i) == 'E')
Also, move the line:
System.out.println(numOfE);
outside one more set of brackets. In total, it should look something like:
case 3: String phrase;
phrase = scan.nextLine();
System.out.println("What is your sentence");
phrase = scan.nextLine();
int numOfE = 0;
for (int i = 0; i < phrase.length(); i++) {
char ch = phrase.charAt(i);
if (ch == 'e' || ch == 'E') {
numOfE++;
}
}
System.out.println(numOfE);
If you are using Java 8, then this is another approach
long count = phrase.chars().filter(ch -> ch == 'e' || ch == 'E' ).count();
Related
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);
}
The below code is supposed to tell the user whether his input is a vowel or consonant or digit less than 1. The program however returns "Vowel" for all capital letters including consonants and whenever a digit is entered "Consonant" is returned. Ex - if a is entered, result = vowel. If b, result = Consonant. If B, result = Vowel (should be Consonant). If 1, result = Consonant(should be Digit) . Any advice would be greatly appreciated. Thanks.
package checkVowelorConstantorNumber;
import java.util.Scanner;
public class Main {
public static void main (String [] args) {
Scanner inp = new Scanner (System.in);
boolean tf = false;
while(tf == false) {
System.out.println("Enter a character which is a - z or A - Z or
less than 1");
char cha = inp.next().charAt(0);
inp.nextLine();
if(Character.isLetter(cha) && cha == 'a'||cha == 'e' || cha == 'i' || cha == 'o' || cha == 'u' || Character.isUpperCase(cha)) {
System.out.println("Vowel");
}
else if(Character.isLetter(cha) && cha != 'a'|| cha != 'e' || cha != 'i' || cha != 'o' || cha != 'u' || Character.isUpperCase(cha)) {
System.out.println("Consonant");
}
else if(Character.isDigit(cha) && cha <= 1 ) {
System.out.println("Digit");
}
else System.out.println("Invalid character");
}
}
}
Your if statement first checks if the given character is a letter and not an a, 1 is neither so that is false, then it checks if 1 is not equal to 'e' causing that statement to be true, thus printing 'Consonant'. You have to make the check for isLetter for every comparison. Therefore i would recommend something like this:
if(Character.isLetter(cha)) {
// Check for vowel or consonant based on letters
} else if(Character.isDigit(cha) && cha <= '1') {
System.out.println("Digit");
} else {
System.out.println("Invalid character");
}
You also should make the if statement for consonant use && instead of ||, since it should be none of the specified chars.
Pay close attention to logical ands (&&), logical ors (||) and parentheses. Consider the following, modified from your code with some comments.
char cha = inp.next().charAt(0);
inp.nextLine();
if (cha.isLetter()) {
// convert to uppercase to simplify the if
char uc = cha.toUpperCase();
if (uc == 'A' || uc == 'E' || uc == 'I' || uc == 'O' || uc == 'U') {
// it's a vowel
} else {
// it's a letter that isn't a vowel (consonant)
}
} else {
// it's not a letter
if (cha.isDigit() && cha < '1') {
// but it is a digit less than 1
} else {
// it's something else (digit not less than '1' or not a digit)
}
}
I have found syntax that is supposed to change the first character from a lowercase letter to an uppercase letter.
For some reason my program won't! When I type a 'm' instead of 'M'.
What am I doing wrong here?
public static void main(String[] args) {
System.out.print("Enter two characters: ");
Scanner input = new Scanner(System.in);
String twoChar = input.nextLine();
if(twoChar.length() > 2 || twoChar.length() <= 1){
System.out.println("You must enter exactly two characters");
System.exit(1);
}
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
if(twoChar.charAt(1) == '1'){
System.out.println("Mathematics Freshman");
}else if(twoChar.charAt(1) == '2'){
System.out.println("Mathematics Sophomore");
}else if(twoChar.charAt(1) == '3'){
System.out.println("Mathematics Junior");
}else if(twoChar.charAt(1) == '4'){
System.out.println("Mathematics Senior");
}
}
Instead of
if(twoChar.charAt(0) == 'M'){
use
if(ch == 'M'){
You are getting the uppercased character, but then not using it.
You are assigning the upper case version of the character to a variable ch, and then you are not checking ch; you are checking the character in the string again. That character is the same as it was before: it is not changed.
So instead of checking:
if (twoChar.charAt(0) == 'M') {
check:
if (ch == 'M') {
Not using the local variable
You aren't using the char ch you uppercased here,
char ch = Character.toUpperCase(twoChar.charAt(0));
if(twoChar.charAt(0) == 'M'){
you might fix it by using the local variable ch like
char ch = Character.toUpperCase(twoChar.charAt(0));
if (ch == 'M') {
or by placing the toUpperCase call in-line like
// char ch = Character.toUpperCase(twoChar.charAt(0));
if (Character.toUpperCase(twoChar.charAt(0)) == 'M') {
or using a logical-or like
char ch = twoChar.charAt(0);
if (ch == 'M' || ch == 'm') {
I am trying to work on a syllable counter that counts the syllables in the string I enter. Here are the instructions. -
Syllables are really useful for a lot of things. They are defined according to the following rules involving
consonants (non-vowels) and vowels (a, e, i, o, u, y):
Starting y omitted:
(a) when words begin with y, we don’t count the starting y as a vowel. (we are
assuming there are no words that start with y followed immediately by a consonant)
Silent e omitted:
(a) when e is the last letter of a word, we’ll assume it is silent, unless the word is café or
entrée (words borrowed from French). (* we’ll ignore all other words to simplify)
For simplification, it may be best to create a new String without this silent e, before
checking for more syllables.
With the silent-e omitted, one-syllable units:
(a) have a single vowel.
(b) have two vowels that are the same letter in succession.
(c) have two vowels in immediate succession that are ei, ie, ea, ou, ey, ay, oy, uy, ai.
(d) have three vowels in immediate succession that are eau, iou (* yes, there are
exceptions to this that we are ignoring here).
With the silent-e omitted, two-syllable units:
(a) two vowels in immediate succession where the vowels are different letters not
following the rule above. For instance, oe, io, oi.
(b) three vowels in immediate succession not following the rule above where the last
vowel is not a silent e. For instance (“eye”) as in “meyer.”
Generate a program called SyllableCounter that counts syllables in a word or sentence (maximum one
line). Assume the user will not use any punctuation. Pseudocode and a testing plan are required.
Do not print in main().
Sample output:
Please enter your word or sentence, followed by a carriage return.
Sally where are you going
Your entry has 7 syllables.
Here is my current code (It compiles, but has a StringIndexOutOfBoundsException -
/*
* SyllableCounter.java
* Prints the number of syllables based on an inputed string
*
* Testing - What should work - All strings with letter characters
* What shouldn't work - Number values
*/
import java.util.Scanner; //import the scanner
public class SyllableCounter //class is SyllableCounter
{
public static void main (String args[]) //main() method header
{
String string = "";
string = getInput(); //call getInput()
int totalCount = calc(string); //call calc()
printOut(totalCount); //call printOut()
}
public static String getInput() //getInput() method
{
Scanner console = new Scanner (System.in); //create an instance of the scanner
System.out.println("Please enter your word or sentence, followed by a carrige return");
String input = console.nextLine(); //get the inputted string and return it
return input;
}
public static int calc (String string)
{
//int finalCount = 0;
//int index = string.indexOf(' ');
return calcWord(string);
}
public static int calcWord(String word) //calc() method
{
int count = 0;
//for loop goes through all charectors
int length = word.length();
for (int i = 0; i<length; i++)
{
if ((word == "entree") || (word == "cafe"))
return 2;
else if (i==0)//if i is 0
{
if (word.charAt(i) == 'a' //if letter is a,e,i,o or u
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u')
count++ ; //count ++
else //else
{} //nothing
}
else if (i==word.length()-1) //else if i is the last letter of the string
{
if ( (word.charAt(i) == 'a') || (word.charAt(i) == 'i') || (word.charAt(i) == 'o') || (word.charAt(i) == 'u') || (word.charAt(i) == 'y') )
//else if letter is a,i,o,u or y (also 2 or 3 in a row)
{
count ++ ;//count ++
}
else //else
{} //nothing
}
else if (word.charAt(word.length()-1) == 'e') {
if (length >= i+2)
if ( word.substring(i,i+3) == "eau"
|| word.substring(i,i+3) == "iou" )
{
count++;
i+=2;
}
else if ( word.substring(i,i+2) == "ei"
|| word.substring(i,i+2) == "ie"
|| word.substring(i,i+2) == "ea"
|| word.substring(i,i+2) == "ou"
|| word.substring(i,i+2) == "ey"
|| word.substring(i,i+2) == "ay"
|| word.substring(i,i+2) == "oy"
|| word.substring(i,i+2) == "uy"
|| word.substring(i,i+2) == "ai" )
{
count++;
i++;
}
else if( word.substring(i, i+2) == "oe"
|| word.substring(i, i+2) == "io"
|| word.substring(i, i+2) == "oi" )
{
count+=2;
i++;
}
}
else {
if (word.charAt(i) =='a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
}
if (!(word.charAt(word.length()-1) == 'e'))
{
if ( word.substring(i,i+3) == "eau")
{
count++;
i+=2;
}
else if (word.charAt(i) == 'a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
}
else if (word.charAt(i) == 'a'
|| word.charAt(i) == 'e'
|| word.charAt(i) == 'i'
|| word.charAt(i) == 'o'
|| word.charAt(i) == 'u' )
{
count++;
}
else //else
{} //nothing
}
return count;//return the count
}
public static void printOut(int count) //printOut() method
{
System.out.println(count);
// print the count
}
}
I used the word "foo" as input to your program:
Here (around line 112 for me) :
if (!(word.charAt(word.length()-1) == 'e')){
if ( word.substring(i,i+3) == "eau")
An example of how the above section of code fails is using the word foo:
The char at word length-1 is not e so therefore this condition above will be evaluated. However, when i is equal to 1 i+3 will equal 4. So, 4 is outside the length of "foo" causing the error.
Keep in mind this is just one example of this type of failure. Make sure that whenever you are getting a substring from i to i+n the string being evaluated has i+n chars left.
Manually finding the solution is a lot of work. Regular Expression could be a sweet solution to your problem. Have a look at the link below:
How to calculate syllables in text with regex and Java
Also be reminded that the above reference doesnot consider Y as a syllable, you will have to tweak the regular expression a bit to get the desired output. Plus the vowel "e" needs some checking to be done to get the exact results.
Sort all words by comparing the number of vowels that each word contains. The
word with the fewest number of vowels would come first. If you have more than one word with the same number of vowels, that group would be sorted alphabetically.
I believe that I have most of the project completed, I just don't know why it's not working.
public class Word implements Comparable<Word> {
private String word;
public Word(String s) {
word = s;
}
private int numVowels() {
String vowels = "AEIOUaeiou";
int vowelCount = 0;
for (int i = 0; i < vowels.length(); i++) {
if ((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u')) {
return vowelCount;
}
}
return vowelCount;
}
public int compareTo(Word rhs) {
for (int i = 0; i < word.length(); i++) {
if ((word.charAt(i) == 'a') || (word.charAt(i) == 'A')) {
System.out.println(word);
} else if ((word.charAt(i + 1) == 'e') || (word.charAt(i + 1) == 'E')) {
System.out.println(word);
}
}
return -1;
}
public String toString() {
return word;
}
}
I think my error is in the compareTo method. I'm not sure. Would anyone be able to help me?
First - I didn't realize that Word was your custom class. That said...there's a lot of flaws with it.
Your compareTo method is really, effectively, only comparing two Strings together. What you want to do is something like this:
public int compareTo(Word other) {
return word.compareTo(other.getWord());
}
The reason for this is that String implements Comparable<String>.
Now, if this isn't what you're going for (and I'm really not sure what that exactly is), then you may look into comparing the number of vowels two Word instances have.
public int compareTo(Word other) {
return word.numVowels() - other.numVowels();
}
The above will return a positive value if the current Word has more vowels than the Word being compared to, a negative value if there are less, or zero if the vowels are equivalent.
Next, your numVowels() method is completely broken. Look at what you're iterating across: vowels. The vowels String is always a constant value. It's never going to change - there are exactly ten vowels, five lower case, and five upper case.
What you want to do is check your word field against the set of vowels.
Here's a better* solution: use a Set<Character> - you get constant look up time for them all.
Set<Character> vowelSet = new HashSet<Character>() {{
add('a');
add('A');
add('e');
add('E');
add('i');
add('I');
add('o');
add('O');
add('u');
add('U');
}};
Then, all you have to do in your loop is this:
int count = 0;
for(char c : word.toCharArray()) {
if(vowelSet.contains(c)) {
count++;
}
}
return count;
*It doesn't take into account that Y is sometimes a vowel.
if((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u') || (vowels.charAt(i) == 'A') || (vowels.charAt(i) == 'E') || (vowels.charAt(i) == 'I') || (vowels.charAt(i) == 'O') || (vowels.charAt(i) == 'U'))
{
vowelCount++;
}
You were previously returning 0 when you returned vowelCount. You need to increment vowelCount when you find vowels and then return it after you're done looping. You also need to check for upper case vowels and not just lower case vowels to get an accurate count.
Your compareTo method is not even close to correct...
First of all, try not to post your Homework on here. Your numVowels() method is wrong too.
private int numVowels() //FIXED METHOD
{
String vowels = "AEIOUaeiou";
int vowelCount = 0;
for(int i = 0; i < vowels.length(); i++)
{
if((vowels.charAt(i) == 'a') || (vowels.charAt(i) == 'e') || (vowels.charAt(i) == 'i') || (vowels.charAt(i) == 'o') || (vowels.charAt(i) == 'u') || (vowels.charAt(i) == 'A') || (vowels.charAt(i) == 'E') || (vowels.charAt(i) == 'I') || (vowels.charAt(i) == 'O') || (vowels.charAt(i) == 'U'))
{
return vowelCount; //Will return lowercase AND capital vowels :)
}
}
return vowelCount;
}
Your original code only searched for lowercase 'a', 'e', 'i', 'o', and 'u'. I added capitals to your if statement ('A', 'E' etc)