I 更改了我的代码,因为丹麦建议。 i 但现在可以编制方案,不管投入是什么,结果总是 2. i 将该方案的第二部分置于新的法典之下。 请提供帮助。
这里是新法典。
public class VowelCons
{
private final String str;
private final int totalConsonants;
private final int totalVowels;
public VowelCons(final String s)
{
this.str = s;
int totalConsonants = 0;
int totalVowels = 0;
if (null != s)
{
for (final char c : s.toCharArray())
{
switch (c)
{
case A :
case a :
case E :
case e :
case I :
case i :
case O :
case o :
case U :
case u :
totalVowels++;
break;
default:
if (Character.isLetter(c))
{
totalConsonants++;
}
break;
}
}
}
this.totalConsonants = totalConsonants;
this.totalVowels = totalVowels;
}
public String getString()
{
return str;
}
public int getNumConsonants()
{
return this.totalConsonants;
}
public int getNumVowels()
{
return this.totalConsonants;
}
}
there s another part of this program which gets the user s input and passes it to this class. Here s the code. [this part cannot be changed according to the regulations]
import java.util.Scanner;
public class VowelConsCounter
{
public static void main(String[] args)
{
String input; // User input
char selection; // Menu selection
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter a string: ");
input = keyboard.nextLine();
VowelCons vc = new VowelCons(input);
do
{
selection = getMenuSelection();
switch(Character.toLowerCase(selection))
{
case a : System.out.println("
Number of vowels: " +
vc.getNumVowels());
break;
case b : System.out.println("
Number of consonants: " +
vc.getNumConsonants());
break;
case c : System.out.println("
Number of vowels: " +
vc.getNumVowels());
System.out.println("Number of consonants: " +
vc.getNumConsonants());
break;
case d : System.out.print("Enter a string: ");
input = keyboard.nextLine();
vc = new VowelCons(input);
}
} while (Character.toLowerCase(selection) != e );
}
public static char getMenuSelection()
{
String input;
char selection;
Scanner keyboard = new Scanner(System.in);
System.out.println("a) Count the number of vowels in the string.");
System.out.println("b) Count the number of consonants in the string.");
System.out.println("c) Count both the vowels and consonants in the string.");
System.out.println("d) Enter another string.");
System.out.println("e) Exit the program.");
input = keyboard.nextLine();
selection = input.charAt(0);
while (Character.toLowerCase(selection) < a || Character.toLowerCase(selection) > e )
{
System.out.print("Only enter a, b, c, d, or e: ");
input = keyboard.nextLine();
selection = input.charAt(0);
}
return selection;
}
}