在另一个方法中调用另一个方法时出错

时间:2017-02-04 09:12:28

标签: java string object methods static

嗨,所以我试着做这个猪拉丁语代码,其中第一个字母从单词中删除并发送到单词的结尾,同时添加" 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 
     */

3 个答案:

答案 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个变量设置在任何位置(strwords)。而是在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;