【发布时间】:2019-12-01 17:21:16
【问题描述】:
看起来很简单,但我是编码新手。我正在尝试设置一个计数器来计算用户输入字符串的每个字母,但我不想计算空格。
我看到很多人推荐使用 replaceAll() 函数,但我还没有了解它,也不知道如何/在哪里定义它。想知道是否有另一种方法,如果没有,如何调用/replaceAll(" ", "") 的语法,以及它在代码中的位置。
import java.util.Scanner;
public class Vowel_Counter
{
public static void main (String[] args)
{
int aCount= 0 , eCount= 0, iCount= 0;
int total= 0, totalConsonant= 0, count = 0;
char vowels= 0, i = 0;
String userInput;
System.out.println("Please enter a string of any lenth, or character combination");
Scanner scan = new Scanner (System.in);
String userIntput = Vowel_Counter.replace(" ","");
userInput = scan.nextLine();
for (count = 0; count < userInput.length(); count++)
{
vowels = userInput.charAt(count);
switch (vowels)
{
case 'a':
aCount++;
break;
case 'e':
eCount++;
break;
case 'i':
iCount++;
break;
}
}
System.out.println("There are " +aCount+ " a's in that string");
System.out.println("There are " +eCount+ " e's in that string");
System.out.println("There are " +iCount+ " i's in that string");
total = userInput.length();
System.out.println("The total lenth is " + total + " charactors");
totalConsonant = total - aCount -eCount -iCount;
System.out.println("There are " + totalConsonant+ " non-vowels in that string");
}
}
如果输入的字符串是“我爱狗”,它应该输出 “有 0 个” “有 1 个 e” “有 1 个我” “总长度为 9 个字符” “有 5 个非元音”
(代码确实包含每个元音的计数器,但我已经为这个问题缩短了它)
【问题讨论】:
-
你当前的输出是多少?
标签: java whitespace removing-whitespace