如何计算空格、元音和字符的数量?


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);
}
}
}  

问题出在哪里?我已经数了三个计数器。我正在 Eclipse 中编码,每当我检查控制台时,我都无法计算字符数。它只是接受输入,而不做任何其他事情。

删除char ch = in.next().charAt(i);,并将ch的其他实例替换为s.charAt(i)

第一次charAt检查也应该a,你必须e两次。

然后将System.out.println...移出循环。

在线演示

只是几个错别字错误。更改您的代码,

String s = in.nextLine().toLowerCase();

char ch = s.charAt(i);

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')

在代码中,使用小写字母与用户输入进行比较。因此,您应该先将用户输入转换为小写。您当前的代码忽略所有大写元音(E,A,I ...(。使用toLowerCase().

通过使用in.next()Scanner正在等待输入。由于您已经使用nextLine()进行了输入,因此您可以使用它。

下一个显然是印刷错误。元音是A,E,I,O,U。

您应该将s = in.next().charAt(i);更改为String s =in.nextLine()并将System.out.println部分放在for循环之外。

还有双"e"(在@Ted霍普的帮助下(:

ch == 'e' || ch == 'e'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);
}

最新更新