我改變了我的代碼爲丹建議我現在可以編譯程序,但是,無論輸入是什麼,結果總是2.我把第二部分這個程序在新代碼下面。請幫忙。除了線程「主」java.lang.NullPointerException -part2
以下是新代碼。
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;
}
}
謝謝大師。我改變了很多我的代碼。因爲這個程序的另一部分將把用戶字符串傳遞給這個類,所以我不能改變很多返回結果。無論如何,我用Dan的建議來重寫VowelCons類。但無論我輸入什麼,結果是2.想知道爲什麼,謝謝大師。 – LPlateJava
對不起隊友,我的錯誤。只是因爲錯誤的方案沒有奏效。但現在我修復它。它完美地工作。非常感謝。 – LPlateJava