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



在java中非常新颖。我正在尝试将方法添加到我目前正在运行的程序中,以从args数组中打印出大量字符。在尝试安装一个新方法时,我在调用args时遇到了问题。这是我当前的代码,红色轮廓是。

static void amountOfCharsInSentence() {
    int sum=0;
    for (String s: args) {  //args on this line is marked red
        sum+=s.length();
    }
}
public static void main(String[] args) {
   amountOfCharsInSentence();
}

任何正确方向的提示都将不胜感激。

argsmain的参数,这意味着您只能在main中使用该参数(类似于局部变量)。

如果你想在其他地方使用它,你有两个选择。最合适的是将其作为参数传递给另一个函数:

static void amountOfCharsInSentence(String[] args) {
// Declare argument here -----------^^^^^^^^^^^^^
    int sum=0;
    for (String s: args) {  // `args` here is the argument to *this* function
        sum+=s.length();
    }
}
public static void main(String[] args) {
    amountOfCharsInSentence(args);
    // Pass it here --------^^^^
}

您的另一个选择是创建类的一个静态成员,类中的所有方法都可以访问该静态成员,并将args分配给该静态成员:

class YourClass {
    static String[] commandLineArgs;
    static void amountOfCharsInSentence() {
        int sum=0;
        for (String s: commandLineArgs) { // Use the static member here
            sum+=s.length();
        }
    }
    public static void main(String[] args) {
        commandLineArgs = args;           // Assign the static member here
        amountOfCharsInSentence();
    }
}

但在这种情况下,这可能不合适。

您尚未传递参数。

static void amountOfCharsInSentence(String[] args) {
int sum=0;
for (String s: args) {  //now it will not give red line. 
                        // red line is indicated because there is no args inside this method
    sum+=s.length();
}
}
 public static void main(String[] args) {
  amountOfCharsInSentence(args);
 }

希望这能解决您的问题

最新更新