在我的循环结束时,我计划在句子中显示辅音和元音的数量。我想知道是否有更有效的方法来检查给定句子中有多少辅音和元音,而不是使用if语句并手动输入每个字母。 (键指的是我已经初始化的扫描仪)
编辑:它需要忽略数字和其他特殊字符,例如,如果我写Hello @你是怎么回事?应该有8个元音和6个辅音。
System.out.println("Please enter the sentence to analyze: ");
String words = key.nextLine(); //the sentence the user inputs
int c = 0; //# of consonants
int v = 0; //# of vowels
int length = words.length(); //length of sentence
int check; //goes over each letter in our sentence
for(check = 0; check < length; check++){
char a = words.charAt(check);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
else if(a == 'b' || a == 'B' || a == 'c' || a == 'C' || a == 'd' || a == 'D' || a == 'f'
|| a == 'F' || a == 'g' || a == 'G' || a == 'h' || a == 'H' || a == 'j' || a == 'J'
|| a == 'k' || a == 'K' || a == 'l' || a == 'L' || a == 'm' || a == 'M' || a == 'n'
|| a == 'N' || a == 'p' || a == 'P' || a == 'q' || a == 'Q' || a == 'r' || a == 'r'
|| a == 's' || a == 'S' || a == 't' || a == 'T' || a == 'v' || a == 'V' || a == 'w'
|| a == 'W' || a == 'x' || a == 'X' || a == 'z' || a == 'Z')
c = c + 1;
}
答案 0 :(得分:4)
使用Character.isLetter(ch)
确定该字符是元音还是辅音,然后检查相关字符是否在元音集中。
创建元音集的一种方法:
Set<Character> vowels = new HashSet<Character>();
for (char ch : "aeiou".toCharArray()) {
vowels.add(ch);
}
并增加v
或c
:
if (Character.isLetter(a)) {
if (vowels.contains(Character.toLowerCase(a))) {
v++;
} else {
c++;
}
}
答案 1 :(得分:2)
假设您已经有一个字母(元音或辅音,不是数字,也不是符号或其他任何东西),那么您可以轻松创建一种方法来定义该字母是否为元音:
static final char[] vowels = { 'a', 'A', 'e', 'E', 'i', 'I', 'o', 'O', 'u', 'U', 'y', 'Y' };
public static boolean isVowel(char c) {
for (char vowel : vowels) {
if (c == vowel) {
return true;
}
}
return false;
}
public static boolean isConsonant(char c) {
return !isVowel(c);
}
请注意,我将Y
和y
设置为元音,因为它们似乎是您的语言。在西班牙语和英语中,Y
是辅音(AFAIK)。
您可以使用Character#isLetter
轻松检查char
是否是一封信。
因此,您的代码将变为:
for(check = 0; check < length; check++){
char a = words.charAt(check);
if (Character.isLetter(a)) {
if (isVowel(a)) {
v++;
} else {
c++;
}
}
}
答案 2 :(得分:2)
像
这样的东西String vowels = "aeiouyAEIOUY"; // you can declare it somewhere before loop to
// to avoid redeclaring it each time in loop
//inside loop
if ((a>='a' && a<='z') || (a>='A' && a<='Z')){ //is letter
if (vowels.indexOf(a)!=-1) //is vowel
v++;
else //is consonant
c++;
}
答案 3 :(得分:2)
我相信这可以改进,但我还是会把它扔进戒指。 从句子中删除非字符,小写它,然后转换为char数组并将其与全部小写的元组字符数组进行比较。
String myText =&#34;这是一个句子。&#34 ;;
int v = 0;
char[] vowels = {'a','e','i','o','u'};
char[] sentence = myText.replaceAll("[^a-zA-Z]","").toLowerCase().toCharArray();
for (char letter : sentence) {
for (char vowel : vowels) {
if (letter == vowel) {
v++;
}
}
}
System.out.println("Vowels:"+ v);
System.out.println("Consonants:" + (sentence.length -v));
答案 4 :(得分:1)
您可以进行范围检查以确保它是一个字母,然后检查它是否是其中一个元音:
if( ( a >= 'a' && a<= 'z' ) || ( a >= 'A' && a <= 'Z' ) )
{
// is letter
switch( a )
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'U': case 'u':
++v;
break;
default: // don't list the rest of the characters since we did the check in the if statement above.
++c;
}
}
答案 5 :(得分:1)
一种简单的方法是创建2个列表:
然后迭代Java字符串中的每个字符。
请参阅以下示例:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Counter {
public static void main(String[] args) {
String test = "the fox is in the woods";
test = test.toLowerCase();
List<Character> vowels = new ArrayList<Character>();
vowels.addAll(Arrays.asList(new Character[]{'a', 'e', 'i', 'o', 'u'}));
List<Character> consonants = new ArrayList<Character>();
consonants.addAll(Arrays.asList(new Character[]{'b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'}));
int vcount = 0;
int ccount = 0;
for (int i = 0; i < test.length(); i++){
Character letter = test.charAt(i);
if (vowels.contains(letter)){
vcount ++;
} else if (consonants.contains(letter)){
ccount++;
}
}
System.out.println(vcount);
System.out.println(ccount);
}
}
答案 6 :(得分:1)
哦,这当然是一种更易读的方式。不确定这是否符合&#34;更好&#34;定义
首先,我建议您将所拥有的内容封装到可以编写一次并随处调用的方法中:
package misc;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ParseUtils get counts of vowels and consonants in sentence
* @author Michael
* @link https://stackoverflow.com/questions/24048907/how-can-i-check-how-many-consonants-and-vowels-there-are-in-a-sentence-in-java
* @since 6/4/2014 6:57 PM
*/
public class ParseUtils {
private static final String VOWEL_PATTERN_STR = "(?i)[aeiou]";
private static final Pattern VOWEL_PATTERN = Pattern.compile(VOWEL_PATTERN_STR);
private static final String CONSONANT_PATTERN_STR = "(?i)[b-df-hj-np-tv-z]";
private static final Pattern CONSONANT_PATTERN = Pattern.compile(CONSONANT_PATTERN_STR);
private ParseUtils() {}
public static void main(String[] args) {
for (String arg : args) {
System.out.println(String.format("sentence: '%s' # letters: %d # vowels: %d # consonants %d", arg, arg.length(), getNumVowels(arg), getNumConsonants(arg)));
}
}
public static int getNumVowels(String sentence) {
return getMatchCount(sentence, VOWEL_PATTERN);
}
public static int getNumConsonants(String sentence) {
return getMatchCount(sentence, CONSONANT_PATTERN);
}
private static int getMatchCount(String s, Pattern p) {
int numMatches = 0;
if ((p != null) && (s != null) && (s.trim().length() > 0)) {
Matcher m = p.matcher(s);
while (m.find()) {
++numMatches;
}
}
return numMatches;
}
}
答案 7 :(得分:0)
按空格分割字符串,并仅计算元音的数量。然后辅音数量=句子长度 - 元音数量。
详细代码:
System.out.println("Please enter the sentence to analyze: ");
int v = 0;
int c = 0;
String string = key.nextLine(); //the sentence the user inputs
String[] stringArray = string.split(" ");
for(int i=0;i<stringArray.length;i++)
{
for(int j= 0; j<string.length(); j++)
{
char a = string.charAt(j);
if(a == 'a' || a == 'A' || a == 'e' || a == 'E' || a == 'i' || a == 'I' || a == 'o'
|| a == 'O' || a == 'u' || a == 'U' || a == 'y' || a == 'Y')
v = v + 1;
}
c= c+(stringArray.length)-v;
}
System.out.println("Vowels:"+v+" and Consonants:"+c);
答案 8 :(得分:0)
一种方法是摆脱非字母,然后元音和辅音,并获取剩下的长度:
public class CountChars {
public static final String CONSONANTS = "[BCDFGHJKLMNPQRSTVWXYZ]";
public static final String VOWELS = "[AEIOU]"; // considering Y a consonant here
public static final String NOT_LETTERS = "[\\W_0-9]";
public static void main(String[] args) {
String words = "How can I check how many consonants and vowels there are in a sentence in Java?";
String letters = words.toUpperCase().replaceAll(NOT_LETTERS, "");
System.out.println("Letters: " + letters.length());
String vowels = letters.replaceAll(CONSONANTS, "");
System.out.println("Vowels: " + vowels.length());
String consonants = letters.replaceAll(VOWELS, "");
System.out.println("Consonants: " + consonants.length());
}
}
答案 9 :(得分:0)
以下是执行此操作的最佳方式:
public static void checkVowelsAndConsonants(String s){
System.out.println("Vowel Count: " + (s.length() - s.toLowerCase().replaceAll("a|e|i|o|u|", "").length()));
//Also eliminating spaces, if any for the consonant count
System.out.println("Consonant Count: " + (s.toLowerCase().replaceAll("a|e|i|o| |u", "").length()));
}