我似乎无法解决这个问题,这是我的第一个Java类,因此非常感谢您的帮助:
这是我到目前为止的事情:
import java.io.Console;
import java.util.Scanner;
public class Pig extends Object{
public static void main( String[] args){
Console console = System.console();
String strEnglishPhrase;
char choice;
do{
System.out.println("Welcome to the Pig Latin Translator!!");
strEnglishPhrase =
console.readLine("Enter Phrase for Translation : ");
Scanner scanner = new Scanner(System.in);
String strEnglishPhrase = scanner.nextLine();
if(strEnglishPhrase != null && !strEnglishPhrase.equals("")){
System.out.println("Phrase in Pig Latin : \n"
+ convertEnglishToPigLatin(strEnglishPhrase));
} else{
System.out.println("Whoops, Invalid Entry.");
}
choice =
console
.readLine("Do you want to continue? y" + '/' + "n?")
.charAt(0);
} while((choice != 'n') && (choice != 'N'));
}
public static String convertEnglishToPigLatin( String strEnglishPhrase){
String strVowels = "aeiou";
String[] strTokens = strEnglishPhrase.split("[ ]");
StringBuffer sbPigLatinStuff = new StringBuffer();
for(int i = 0; i < strTokens.length; i++){
if(strVowels.indexOf(strTokens[i].charAt(0)) >= 0){
sbPigLatinStuff.append(strTokens[i] + "way ");
} else if((strTokens[i].indexOf("a") < 0)
&& (strTokens[i].indexOf("e") < 0)
&& (strTokens[i].indexOf("i") < 0)
&& (strTokens[i].indexOf("o") < 0)
&& (strTokens[i].indexOf("u") < 0)){
sbPigLatinStuff.append(strTokens[i] + "ay ");
} else{
for(int j = 1; j < strTokens[i].length(); j++){
if(strVowels.indexOf(strTokens[i].charAt(j)) >= 0){
sbPigLatinStuff.append(strTokens[i].substring(j)
+ strTokens[i].substring(0, j) + "ay ");
break;
}
}
}
}
return sbPigLatinStuff.toString();
}
}
最佳答案
您在同一范围内有一个字符串变量strEnglishPhrase的双重声明。
public class Pig extends Object
{
public static void main(String[] args)
{
Console console = System.console();
// First declaration of strEnglishPhrase!
String strEnglishPhrase;
char choice;
do {
System.out.println("Welcome to the Pig Latin Translator!!");
strEnglishPhrase = console.readLine("Enter Phrase for Translation : ");
Scanner scanner = new Scanner(System.in);
// Second and duplicate declaration of strEnglishPhrase!
String strEnglishPhrase = scanner.nextLine();
...
}
...
}
}
您可以通过在do循环中删除strEnglishPhrase的类型声明来解决该问题:
// Replace this line
String strEnglishPhrase = scanner.nextLine();
// by this line:
strEnglishPhrase = scanner.nextLine();