2013-10-17 128 views
0

是否可以創建此子模塊?當所有代碼都在main中時,代碼工作正常,而不是作爲子模塊。創建子模塊FOR循環

{ 
    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; 

    } 
    } 

回答

0

您不能在一個方法內移動一段代碼。你必須小心地將代碼中需要的所有變量作爲參數傳遞給該方法,或者在方法本身中聲明它們;否則代碼將無法訪問它們,因爲它們位於不同的「scope」中。

對於您的情況,所有變量都在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; 
} 

我搬到你numberinWeight變量方法體,並更名爲inWeightresult以避免與方法本身的混亂。另請注意,您返回的是用戶輸入的最後一個數字,而不是總重量。