我按照 Dan 的建议更改了我的代码,我现在可以编译该程序,但是,无论输入是什么,结果始终为 2。我将该程序的第二部分放在新代码的下方。请帮忙。
这是新代码。
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;
}
}
该程序的另一部分获取用户的输入并将其传递给此类。这是代码。【此部分不能按规定更改】
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("\nNumber of vowels: " +
vc.getNumVowels());
break;
case 'b' : System.out.println("\nNumber of consonants: " +
vc.getNumConsonants());
break;
case 'c' : System.out.println("\nNumber 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;
}
}