【问题标题】:Variable Not Being Initialized in Function变量未在函数中初始化
【发布时间】:2016-09-23 21:14:28
【问题描述】:

我正在尝试创建一个提示用户输入单词并返回单词长度的程序。但是我遇到了“字符串字;”的问题,因为我不断收到局部变量可能尚未初始化的错误。

 import javax.swing.JOptionPane;

public class FunctionsTest {

  public static void main(String[] args) {

    String word;

    JOptionPane.showMessageDialog(null, "The length of the word is" + findLength (word));

}//End of Main Method

public static int findLength(String word) {

    String str = new String(word);

    return str.length();

 }//End of findLength Method
}

【问题讨论】:

  • 您要查找哪个单词的长度?您从不提供任何信息,您希望您的程序如何工作以及您希望它做什么?

标签: java string variables methods initialization


【解决方案1】:

没有提示用户输入,因此字符串单词永远不会有值。创建用户输入提示,并让字符串等于输入的值。

【讨论】:

    【解决方案2】:

    “word”没有值,它是空的,你需要给“word”一些值:

    String word = "abc";
    

    【讨论】:

      猜你喜欢
      • 2014-05-19
      • 2021-07-08
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      • 2020-09-27
      • 2015-02-19
      相关资源
      最近更新 更多