Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为循环创建子模块_Java_Loops_For Loop - Fatal编程技术网

Java 为循环创建子模块

Java 为循环创建子模块,java,loops,for-loop,Java,Loops,For Loop,是否可以创建此子模块?当所有代码都在main中时,代码运行良好,只是不作为子模块 { public static void main (String [] arsg) { int number, inWeight, weight; boolean veriWeight; weight=inWeight(); System.out.println("Avera

是否可以创建此子模块?当所有代码都在main中时,代码运行良好,只是不作为子模块

    {
    public static void main (String [] arsg)
            {
            int  number, inWeight, weight;
            boolean veriWeight;
            weight=inWeight();

            System.out.println("Average month weight is "+(weight/12));
            System.exit(0);
            }
                   private static int inWeight ();
                   {
                   for (int i=1; i<=12; i++)
                      {
                      number=ConsoleInput.readInt("enter month weight");
                      while (number<=0)
                        {
                        System.out.println("error, try again");
                        number=ConsoleInput.readInt("enter month weight");
                        }
                        inWeight += number;
                        }
                        return number;

    }
    }
{
公共静态void main(字符串[]arsg)
{
整数,重量,重量;
布尔绝对权;
重量=英寸重量();
System.out.println(“月平均重量为”+(重量/12));
系统出口(0);
}
私有静态intinweight();
{

对于(int i=1;i您不能只在方法中移动一块代码。您必须小心地将代码中需要的所有变量作为参数传递给该方法,或者在方法本身的主体中声明它们;否则代码无法访问它们,因为它们位于不同的“”中

在您的情况下,所有变量都在
main
方法中声明,因此在
inWeight
方法中需要时,这些变量不可用。请将代码更改为类似于此的内容,这样就可以工作了

public static void main (String [] arsg) {
    int weight = inWeight();
    System.out.println("Average month weight is " + (weight / 12));
}

private static int inWeight() {
    int result = 0;
    for (int i=1; i<=12; i++) {
        int number = ConsoleInput.readInt("enter month weight");
        while (number <= 0) {
            System.out.println("error, try again");
            number = ConsoleInput.readInt("enter month weight");
        }
        result += number;
    }
    return result;
}
publicstaticvoidmain(字符串[]arsg){
整数权重=整数权重();
System.out.println(“月平均重量为”+(重量/12));
}
私有静态int inWeight(){
int结果=0;
对于(int i=1;i