gpt4 book ai didi

java - strEnglishPhrase 已在 main(java.lang.String[]) 中定义?

转载 作者:行者123 更新时间:2023-12-01 19:19:50 25 4
gpt4 key购买 nike

我似乎无法让它工作,这是我的第一个 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();

关于java - strEnglishPhrase 已在 main(java.lang.String[]) 中定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4826115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com