嗨,所以我试着做这个猪拉丁语代码,其中第一个字母从单词中删除并发送到单词的结尾,同时添加" ay"到最后的结果。我已经完成了我应该输出正确结果的所有代码,除了我的问题是实际输出代码。我在用户输入句子后立即收到错误消息。
这是我的代码:
package piglatin;
import java.util.Scanner;
public class PigLatinTest {
public static String str;
public static String[] words;
public static String[] printLatinWords()
{
System.out.println("Enter a Sentence: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
words = str.split(" ");
//System.out.println(words);
return words;
}
public static String[] printPigLatinWords()
{
for (int i = 0; i < words.length; i++) {
char firstLetter = words[i].charAt(0);
words[i] = words[i].substring(1);
words[i] = words[i] + firstLetter + "ay";
//System.out.println(words[i]);
//If you want the words to be in the same line, then this could help instead of System.out.println:
System.out.print(words[i] + " ");
}
return words;
}
public static void main(String[] args)
{
words = printLatinWords();
}
}
/*
Enter a Sentence:
Hello from the other side
*/
答案 0 :(得分:3)
您拥有static
个成员,并使用局部变量对其进行遮蔽。您正在设置局部变量的值,而您的static
成员仍然未初始化。建议:
public static String[] printLatinWords()
{
System.out.println("Enter a Sentence: ");
Scanner scanner = new Scanner(System.in);
str = scanner.nextLine();
words = str.split(" ");
//System.out.println(words);
return words;
}
当然,words
必须是数组而不是String
然后:
public static String[] words;
编辑:
由于您有一组String
个项目,因此您需要对其进行迭代:
public static String[] printPigLatinWords()
{
for (int i = 0; i < words.length; i++) {
char firstLetter = words[i].charAt(0);
words[i] = words[i].substring(1);
words[i] = words[i] + firstLetter + "ay";
System.out.println(words[i]);
//If you want the words to be in the same line, then this could help instead of System.out.println:
//System.out.print(words[i] + " ");
}
return words;
}
EDIT2:
main
方法建议:
public static void main(String[] args)
{
printLatinWords();
printPigLatinWords();
}
答案 1 :(得分:1)
假设错误是我认为的错误,您不会将public static
个变量设置在任何位置(str
和words
)。而是在printLatinWords
方法中设置局部变量。
我建议你做两件事之一:
答案 2 :(得分:1)
试
在 main()方法
中words = printLatinWords();
你在printPigLatinWords()方法里面
String word = words[0];
char firstLetter = word.charAt(0);
word = word.substring(1);
word = words[0] + firstLetter + "ay";
return word;