我正在用Java编写一个程序,如果您输入“此字符串具有元音和12345位数字”,则应该给出这样的输出:
元音= 8
upper = 2
数字= 5
空白= 6
元音i出现最多= 4
我的代码可以编译,除了确定哪个元音出现最多之外,我在所有方面都取得了成功。我不确定应该使用什么,首先计算单个元音(如“ a”)的出现次数(而不是字符串中总元音的数量)。在找到每个元音的总数之后,我不确定要用什么来确定最大值的元音。一旦能够完成这两个步骤,就不能确定如何正确输出。我宁愿使用if语句来完成此操作,但是我不知道这是否可行。
任何帮助/提示将不胜感激,这是我编写的代码:
import java.util.*;
public class program4
{
public static void main (String []args)
{
Scanner scan = new Scanner(System.in);
String str;
char ch;
int vowels = 0;
int vowelA = 0; int vowelE = 0; int vowelI = 0; int vowelO = 0; int
vowelU = 0;
int maxVowels = 0;
int upper = 0;
int digits = 0;
int whitespace = 0;
str = scan.nextLine();
// use charAt to see each character
// use length to know how many characters are in the String
// loop through each character of the String
// for number of VOWELS
for (int i = 0; i < str.length(); i++)
{
ch = str.charAt(i);
ch = Character.toLowerCase(ch);
// is this a vowel
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
{
vowels++;
}
// which vowel occurs the most
if (ch == 'a')
vowelA++;
else if (ch == 'e')
vowelE++;
else if (ch == 'i')
vowelI++;
else if (ch == 'o')
vowelO++;
else if (ch == 'u')
vowelU++;
if (vowelA > vowelE && vowelA > vowelI && vowelA > vowelO && vowelA > vowelU)
{
maxVowels = vowelA;
}
}
// for number of UPPERCASE letters
for (int i = 0; i < str.length(); i++)
{
ch = str.charAt(i);
if (ch >= 'A' && ch <= 'Z')
upper++;
}
// for number of DIGITS
for (int i = 0; i < str.length(); i++)
{
ch = str.charAt(i);
if (ch == '0' || ch == '1' || ch == '2' || ch == '3' || ch == '4' || ch == '5' || ch == '6' || ch == '7' || ch == '8' || ch == '9')
digits++;
}
// for number of WHITESPACE characters
for (int i = 0; i < str.length(); i++)
{
ch = str.charAt(i);
if (ch == ' ')
whitespace++;
}
// output
System.out.println("vowels = " + vowels);
System.out.println("upper = " + upper);
System.out.println("digits = " + digits);
System.out.println("whitespace = " + whitespace);
System.out.println("vowel" + " " + "occurs the most = " + maxVowels);
}
}
可以有很多方法。我正在写其中之一。您可以尝试:
尝试此代码:
如果您对基于流的解决方案感兴趣: