2015-05-01 28 views
0

我已經創建了數組,並在其類的外部創建了一個對數組進行排序的方法。它一直說它找不到我所做的數組的變量名稱。當我採用這個方法並將它放入與它的數組相同的類中時,它會破壞我試圖達到的目的,幫助嗎?爲什麼我不能在類之外的方法中使用數組?

/** 
* @param args the command line arguments 
*/ 
    public static void main(String[] args) { 
     // TODO code application logic here 

     System.out.println("Enter a length for the array: "); 
     Scanner scan = new Scanner(System.in); 
     int x = scan.nextInt(); 

     int randomNumbers[] = new int[x]; 

     for (int index = 0; index < randomNumbers.length; index++) 

     { 
      randomNumbers[index] = (int) (Math.random() * 100); 
     } 

     for (int index = 0; index < randomNumbers.length; index++) 

     { 
      System.out.println(randomNumbers[index]); 
     } 

    } 

    static void sortAscending() 

    { 
     Arrays.sort(randomNumbers); 

     for (int i = 1; i < randomNumbers.length; i++) { 
      System.out.println("Number: " + randomNumbers[i]); 
     } 
    } 
+1

通行證'randomNumbers'作爲方法的參數。如果你需要返回'array'而不是僅僅打印東西,'返回'它。 – Mena

+0

我正在處理一個問題,要求我編寫sortAscending和一個降序的方法,我創建了它們,但是如何返回數組而不是打印。 –

+1

可怕的代碼格式。如果你想要某人幫助你,請花點功夫來正確地問你的問題(格式等) –

回答

2

由於randomNumbers宣佈在main方法,其他方法不能訪問它。有幾種方法,使陣列與其他方法訪問,例如:

  1. 通作爲參數傳遞給方法:

    static void sortAscending(int[] randomNumbers) { 
        //... 
    } 
    

    ,並呼籲從mainsortAscending這樣調用

    sortAscending(randomNumbers); 
    
  2. 通過字段傳遞值。但是,我不會使用靜態字段,因爲所有實例只有這些字段中的一個。但是你可以利用你的類的實例和值存儲在非靜態字段:

    publc class MyClass { 
    
        // declare randomNumbers as field 
        private int[] randomNumbers; 
    
        public static void main(String[] args) { 
         MyClass o = new MyClass(); 
         o.localMain(args); 
    
         // you could call sortAscending here like this 
         o.sortAscending(); 
        } 
    
        // you don't really need to pass args, since you don't use it 
        public void localMain(String[] args) { 
         // TODO code application logic here 
    
         System.out.println("Enter a length for the array: "); 
         Scanner scan = new Scanner(System.in); 
         int x = scan.nextInt(); 
    
         // assing new value to field 
         randomNumbers = new int[x]; 
    
         for (int index = 0; index < randomNumbers.length; index++) 
         { 
          randomNumbers[index] = (int) (Math.random() * 100); 
         } 
    
         for (int index = 0; index < randomNumbers.length; index++) 
         { 
          System.out.println(randomNumbers[index]); 
         } 
    
        } 
    
        void sortAscending() 
        { 
         Arrays.sort(randomNumbers); 
    
         for (int i = 1; i < randomNumbers.length; i++) { 
          System.out.println("Number: " + randomNumbers[i]); 
         } 
        } 
    
    } 
    
+0

很好的回答,謝謝! –

相關問題