我需要同时计算元音和辅音,但我对辅音感到困惑。

huangapple go评论65阅读模式
英文:

I need to count both vowels and consonants but i am stumped on the consonants

问题

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);

        System.out.println("输入一些文本:");
        String str = in.nextLine();
        System.out.println(str);

        System.out.print("你的输入中有 " + count_Vowels(str) + " 个元音字母");
        System.out.print("和 " + count_Consonants(str) + " 个辅音字母");
    }

    public static int count_Vowels(String str) {
        int vcount = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vcount++;
            }
        }
        return vcount;
    }

    public static int count_Consonants(String str) {
        int ccount = 0;
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            if (ch >= 'a' && ch <= 'z') {
                if (ch != 'a' && ch != 'e' && ch != 'i' && ch != 'o' && ch != 'u') {
                    ccount++;
                }
            }
        }
        return ccount;
    }
}
英文:

I can't figure out how to have both vowels and consonants. The vowels part of the code works fine. I have no idea how to add the consonants.

import java.util.Scanner;
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.println(&quot;Enter some text: &quot;);
String str = in.nextLine();
System.out.println(str);
System.out.print(&quot;your input has &quot; + count_Vowels(str) + &quot;vowels&quot;);
}
public static int count_Vowels(String str)
{
int vcount = 0;
for (int i = 0; i &lt; str.length(); i++)
{
char ch = str.charAt(i);
if (ch == &#39;a&#39; || ch == &#39;e&#39; || ch == &#39;i&#39; || ch == &#39;o&#39; || ch == &#39;u&#39;)
{
vcount++;
}
}
return vcount;
}
public static int count_Consanants(String str)
{
int ccount = 0;
for (int i = 0; i &lt; str.length(); i++)
{
char ch = str.charAt(i);
if (ch == &#39;a&#39; || ch == &#39;e&#39; || ch == &#39;i&#39; || ch == &#39;o&#39; || ch == &#39;u&#39;)
{
vcount++;
}
else
{
consonants++;
}
}
}  
}

I cannot seem to figure out the consonant part of the code

答案1

得分: 1

Your code will also count other characters that are not consonants. Here is a simple way to count vowels and consonants:

for (int i = 0; i < str.length(); i++) {    
    //Checks whether a character is a vowel
    if (str.charAt(i) == 'a' || str.charAt(i) == 'e' || str.charAt(i) == 'i' || str.charAt(i) == 'o' || str.charAt(i) == 'u') {      
        vCount++;    
    }    
    //Checks whether a character is a consonant    
    else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {        
        cCount++;    
    }    
}

Similarly, you can also modify the code for upper case characters.


Slightly elegant:

Set<Character> vowels = new HashSet<>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
   
for (int i = 0; i < str.length(); i++) {
    char c = str.charAt(i);
    if (vowels.contains(c)) {
        vCount++;
    } else if (c >= 'a' && c <= 'z') {
        cCount++;
    }
}
英文:

Your code will also count other characters that are not consonants. Here is a simple way to count vowels and consonants:

for (int i = 0; i &lt; str.length(); i++) {    
//Checks whether a character is a vowel
if (str.charAt(i) == &#39;a&#39; || str.charAt(i) == &#39;e&#39; || str.charAt(i) == &#39;i&#39; || str.charAt(i) == &#39;o&#39; || str.charAt(i) == &#39;u&#39;) {      
vCount++;    
}    
//Checks whether a character is a consonant    
else if (str.charAt(i) &gt;= &#39;a&#39; &amp;&amp; str.charAt(i)&lt;=&#39;z&#39;) {        
cCount++;    
}    
}    

Similarly, you can also modify the code for upper case characters.


Slightly elegant:

Set&lt;Character&gt; vowels = new HashSet&lt;&gt;(Arrays.asList(&#39;a&#39;, &#39;e&#39;, &#39;i&#39;, &#39;o&#39;, &#39;u&#39;));
for (int i = 0; i &lt; str.length(); i++) {
char c = str.charAt(i);
if (vowels.contains(c)) {
vCount++;
} else if (c &gt;= &#39;a&#39; &amp;&amp; c &lt;= &#39;z&#39;) {
cCount++;
}
}

答案2

得分: 0

以下是一种实现方法。

  • 首先,将字符串转换为小写,以便于搜索。
  • 然后,设置一个字符串表示元音字母。如果要计算字母 y,可以将其添加进去。
  • 主要部分通过循环遍历数组,确保字符是字母,并计算计数。仅检查字母很重要,因为空格和标点符号可能会影响结果。
Scanner in = new Scanner(System.in);

System.out.println("输入一些文本:");
String str = in.nextLine().toLowerCase();
String vowels = "aeiou";
System.out.println(str);

int vcount = 0;
int ccount = 0;

for (char c : str.toCharArray()) {
    if (Character.isLetter(c)) {
        if (vowels.indexOf(c) >= 0) {
            vcount++;
        } else {
            // 必须是辅音
            ccount++;
        }
    }
}
System.out.printf("共有 %d 个元音和 %d 个辅音%n",
        vcount, ccount);
英文:

Here is one way to do it.

  • First it converts the string to lower case to facilitate the search
  • Then it sets a string to the vowels. You may want to add y if you're counting that
  • The main part loops thru the array, ensuring the character is a letter, and then tallying the counts. It is important to only check letters since spaces and punctuation marks could throw off the results.
Scanner in = new Scanner(System.in);
System.out.println(&quot;Enter some text: &quot;);
String str = in.nextLine().toLowerCase();
String vowels = &quot;aeiou&quot;;
System.out.println(str);
int vcount = 0;
int ccount = 0;
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
if (vowels.indexOf(c) &gt;= 0) {
vcount++;
} else {
// must be a consonant
ccount++;
}
}
}
System.out.printf(&quot;There were %d vowels and %d consonants%n&quot;,
vcount, ccount);
</details>
# 答案3
**得分**: 0
# 淘汰法过程
你说:
&gt;我在辅音上感到困惑
基本思想是,在你已经测试了字符是否(a)为拉丁字母的一部分,(b)是一个字母(不是数字、标点等),以及(c)不是元音之后,你可以假定你有一个辅音。
正如你在下面的代码示例中所看到的,我们使用级联的`if`语句检查每个字符,这里摘要为伪代码:
if( … 不属于拉丁字母表,比如韩文或表情符号 )
{
other++;
}
else if( … 不是字母,比如数字或标点符号 )
{
other++;
} 
else if ( … 明确是元音 )
{  
vowel++;
} 
else if ( … 可能是元音(`y`) )
{  
maybeVowel++;
} 
else  // 否则肯定不是元音,所以一定是辅音。
{  
consonant++;
}
# `char` 已过时
前两个答案基本上是对的,但使用了已经过时的 `char` 类型。该类型只能处理 Unicode 定义的 140,000 多个字符的不到一半。而且这些答案假定只有英语,没有变音符号等。
# Unicode 代码点
相反,养成使用整数的 [代码点][2] 习惯。
String input = "😷 带医疗口罩的脸" ;
为文本中的每个字符创建一个代码点数的流。
IntStream intStream = input.codePoints() ;
从流中创建一个数组。
int[] codePoints = intStream.toArray();
循环处理每个代码点。
for ( int codePoint : codePoints )
{
…
}
首先检查字符是否在 [Unicode 中定义的拉丁字母表][3] 内。参考 [*如何判断 Unicode 代码点是否表示某个特定字母表(如拉丁字母)的字符?*](https://stackoverflow.com/q/62109781/642706)。
if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) ) { … } else { other ++ ; ) 
接下来,我们必须测试这个字符是否是字母。
if ( Character.isLetter( codePoint ) ) { … } else { other ++ ; )  
为了简化比较,我们应该转换为小写。
int lowercaseCodePoint = Character.toLowerCase( codePoint );
接下来测试元音。我不知道 Java 或 Unicode 是否提供了元音与辅音的测试。因此,我们必须自己定义一组元音。我不了解所有基于拉丁字母表的语言,但至少我可以涵盖英语元音。当然,`y` 很棘手,所以我将把它计为 `maybeVowel` 计数。
int[] vowelCodePoints = "aeiou".codePoints().toArray();
int[] maybeVowelCodePoints = "y".codePoints().toArray();
我们将查看这些数组是否包含每个字符的代码点数。因此,对数组进行排序以启用二进制搜索。
Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );
添加元音测试。
if ( Arrays.binarySearch( vowelCodePoints , lowercaseCodePoint ) >= 0 )
添加可能元音测试。
else if ( Arrays.binarySearch( maybeVowelCodePoints , lowercaseCodePoint ) >= 0 )
如果我们通过了这两个与元音相关的测试,我们可以假设我们的非元音小写拉丁字母是一个辅音。
将所有代码放在一起。
String input = "😷 带医疗口罩的脸";
IntStream intStream = input.codePoints();
int[] codePoints = intStream.toArray();
int[] vowelCodePoints = "aeiou".codePoints().toArray();
int[] maybeVowelCodePoints = "y".codePoints().toArray();
// 将这些数组排序以启用二进制搜索。
Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );
int vowel = 0;
int maybeVowel = 0;
int consonant = 0;
int other = 0;
for ( int codePoint : codePoints )
{
if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) )
{
if ( Character.isLetter( codePoint ) )
{
int lowercaseCodePoint = Character.toLowerCase( codePoint );
if ( Arrays.binarySearch( vowelCodePoints , lowercaseCodePoint ) >= 0 )
{  // 如果肯定是元音…
vowel++;
} else if ( Arrays.binarySearch( maybeVowelCodePoints , lowercaseCodePoint ) >= 0 )
{  // 否则如果可能是元音…
maybeVowel++;
} else
{  // 否则这个非元音小写拉丁字母一定是辅音。
consonant++;
}
} else { other++; }  // 否则不是字母。
} else { other++; }      // 否则不在拉丁字母表内。
}
在控制台输出。
// 报告
System.out.println( "RESULTS  ----------------------------------------------" );
System.out.println( "input = " + input );
System.out.println( "codePoints = " + Arrays.toString( codePoints ) );
System.out.println( "Count code points: " + codePoints.length );
System.out.println( "vowelCodePoints = " + Arrays.toString( vowelCodePoints ) );
System.out.println( "maybeVowelCodePoints = " + Arrays.toString( maybeVowelCodePoints ) );
System.out.println( "vowel = " + vowel );
System.out.println( "maybeVowel = " + maybeVowel );
System.out.println( "consonant = " + consonant );
System.out.println( "other = " + other );
System.out.println( "vowel + maybeVowel+consonant+other = " + ( vowel + maybeVowel + consonant + other ) );
System.out.println( "END  ----------------------------------------------" );
# 示例用法
运行时
<details>
<summary>英文:</summary>
# Process of elimination
You said:
&gt;i am stumped on the consonants
The basic idea is that after you have tested for the character being (a) of the Latin-script, (b) being a letter (not a digit, punctuation, etc.), and (c) not a vowel, you can assume you have a consonant. 
As you can see at the center of the code example below, we examine each character with a cascading `if` statement, summarized here as pseudo-code:
if( … not part of the Latin script, such as Korean or emoji )
{
other++;
}
else if( … not a letter, such as digit or punctuation )
{
other++;
} 
else if ( … definitely a vowel )
{  
vowel++;
} 
else if ( … maybe a vowel (`y`) )
{  
maybeVowel++;
} 
else  // Else definitely not a vowel, so it must be a consonant. 
{  
consonant++;
}
# `char` is legacy
The first two Answers are basically right, but use the obsolete `char` type.  That type handles less than half of the over 140,000 characters defined in [Unicode][1]. And those Answers assume only English without diacriticals and such.
# Unicode code point
Instead, make a habit of using [code point][2] integer numbers instead. 
String input = &quot;&#128567; Face with Medical Mask&quot; ;
Make a stream of the code point numbers for each character in the text.
IntStream intStream = input.codePoints() ;
Materialize an array from the stream. 
int[] codePoints = intStream.toArray();
Loop each code point.
for ( int codePoint : codePoints )
{
…
}
First see if the character is within the [Latin script defined in Unicode][3]. See [*Identify if a Unicode code point represents a character from a certain script such as the Latin script?*](https://stackoverflow.com/q/62109781/642706).
if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) ) { … } else { other ++ ; ) 
Next we must test if this character is a letter or not.
if ( Character.isLetter( codePoint ) ) { … } else { other ++ ; )  
To simplify our comparisons, we should convert to lowercase.
int lowercaseCodePoint = Character.toLowerCase( codePoint );
Next test for vowels. I do not know that Java or Unicode provides a test for vowel versus consonant. So we must define a set of vowels ourselves. I do not know about all Latin-based languages, but I can at least cover English vowels. Of course, `y` is tricky, so I will count that as in a `maybeVowel` count.
int[] vowelCodePoints = &quot;aeiou&quot;.codePoints().toArray();
int[] maybeVowelCodePoints = &quot;y&quot;.codePoints().toArray();
We will want to see if those arrays contain each character&#39;s code point number. So sort the arrays to enable a binary search.
Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );
Add a test for vowel.
if ( Arrays.binarySearch( vowelCodePoints , lowercaseCodePoint ) &gt;= 0 )
Add a test for maybe vowel.
else if ( Arrays.binarySearch( maybeVowelCodePoints , lowercaseCodePoint ) &gt;= 0 )
And if we get past both those vowel-related tests, we can assume our non-vowel lowercase Latin-script character is a consonant.
Put all the code together.
String input = &quot;&#128567; Face with Medical Mask&quot;;
IntStream intStream = input.codePoints();
int[] codePoints = intStream.toArray();
int[] vowelCodePoints = &quot;aeiou&quot;.codePoints().toArray();
int[] maybeVowelCodePoints = &quot;y&quot;.codePoints().toArray();
// Sort those arrays to enable binary search.
Arrays.sort( vowelCodePoints );
Arrays.sort( maybeVowelCodePoints );
int vowel = 0;
int maybeVowel = 0;
int consonant = 0;
int other = 0;
for ( int codePoint : codePoints )
{
if ( Character.UnicodeScript.LATIN.equals( Character.UnicodeScript.of( codePoint ) ) )
{
if ( Character.isLetter( codePoint ) )
{
int lowercaseCodePoint = Character.toLowerCase( codePoint );
if ( Arrays.binarySearch( vowelCodePoints , lowercaseCodePoint ) &gt;= 0 )
{  // If definitely a vowel…
vowel++;
} else if ( Arrays.binarySearch( maybeVowelCodePoints , lowercaseCodePoint ) &gt;= 0 )
{  // Else if maybe a vowel…
maybeVowel++;
} else
{  // Else this non-vowel lowercase letter from Latin-script must be a consonant.
consonant++;
}
} else { other++; }  // Else not a letter.
} else { other++; }      // Else not in Latin script.
}
Dump to console.
// Report
System.out.println( &quot;RESULTS  ----------------------------------------------&quot; );
System.out.println( &quot;input = &quot; + input );
System.out.println( &quot;codePoints = &quot; + Arrays.toString( codePoints ) );
System.out.println( &quot;Count code points: &quot; + codePoints.length );
System.out.println( &quot;vowelCodePoints = &quot; + Arrays.toString( vowelCodePoints ) );
System.out.println( &quot;maybeVowelCodePoints = &quot; + Arrays.toString( maybeVowelCodePoints ) );
System.out.println( &quot;vowel = &quot; + vowel );
System.out.println( &quot;maybeVowel = &quot; + maybeVowel );
System.out.println( &quot;consonant = &quot; + consonant );
System.out.println( &quot;other = &quot; + other );
System.out.println( &quot;vowel + maybeVowel+consonant+other = &quot; + ( vowel + maybeVowel + consonant + other ) );
System.out.println( &quot;END  ----------------------------------------------&quot; );
# Example usage
When run.
&lt;!-- language: lang-none --&gt;
RESULTS  ----------------------------------------------
input = &#128567; Face with Medical Mask
codePoints = [128567, 32, 70, 97, 99, 101, 32, 119, 105, 116, 104, 32, 77, 101, 100, 105, 99, 97, 108, 32, 77, 97, 115, 107]
Count code points: 24
vowelCodePoints = [97, 101, 105, 111, 117]
maybeVowelCodePoints = [121]
vowel = 7
maybeVowel = 0
consonant = 12
other = 5
vowel + maybeVowel+consonant+other = 24
END  ----------------------------------------------
----------
**Tip:** Read the humorous article, [*The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)*](https://www.joelonsoftware.com/2003/10/08/the-absolute-minimum-every-software-developer-absolutely-positively-must-know-about-unicode-and-character-sets-no-excuses/).
[1]: https://en.wikipedia.org/wiki/Unicode
[2]: https://en.wikipedia.org/wiki/Code_point
[3]: https://en.wikipedia.org/wiki/Latin_script_in_Unicode
</details>

huangapple
  • 本文由 发表于 2020年5月31日 05:50:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/62109094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定