2014-02-26 123 views
1

我知道我應該理解如何做到這一點,但對於我的生活,我似乎無法如何傳遞int [] array1並將其設置爲等於int [] toSort下面。當試圖通過時,我不斷收到未找到的錯誤變量。感謝您的支持和幫助。具有從覆蓋傳遞數組

public class LoadListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // Let the user pick the file 
      JFileChooser pickFile = new JFileChooser(); 
      String fileName = "boo"; 
      Scanner input; 
      if(pickFile.showOpenDialog(mPanel) == JFileChooser.APPROVE_OPTION) { 
       fileName = pickFile.getSelectedFile().getAbsolutePath(); 
       System.out.println(fileName); 
       try { 
        input = new Scanner(new File(fileName)); 
        StringBuffer data = new StringBuffer(""); 
        while(input.hasNextLine()) { 
         String t = input.nextLine(); 
         System.out.println("Line to add: " + t); 
         data.append(t); 

        } 

        input.close(); 
        unsortedList.setText(data.toString()); 

        String[] ss = ((unsortedList.getText()).replaceAll(" ",  ",")).split(fileName);     

        int[] array1 = new int[ss.length]; 
        for (int i=0; i < ss.length; i++) { 
         array1[i] = Integer.parseInt(ss[i]); 
        } 




       } 
       catch(FileNotFoundException ex) { 
        JOptionPane.showMessageDialog(mPanel, "Error opening" + 
          " and/or processing file: " + fileName, 
          "File Error", JOptionPane.ERROR_MESSAGE); 
        System.out.println(ex); 
       } 
      } 
     } 
    } 


    private class ButtonListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      StringBuffer dataSorted = new StringBuffer(""); 

      // TODO: Get the list from the TextArea 
      int[] toSort = array1; 
+3

您應該閱讀* Java變量作用域*。 – Christian

回答

1

array1範圍僅在LoadListener類的actionPerformed()方法,並正在從另一個類ButtonListener的另一種方法進行存取。這在java中是非法的

你不能從另一個方法訪問,一個方法局部變量。有關更多詳細信息,請閱讀oracle doc

0

@ user3354341:嘗試下面的代碼,它將解決您的問題,並且還需要了解Java中變量的作用域,因爲您試圖訪問一個類的局部變量進入另一個班級。

public class LoadListener implements ActionListener { 

     private int[] array1; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      ... 
      String[] ss = ((unsortedList.getText()).replaceAll(" ",  ",")).split(fileName); 
      array1 = new int[ss.length]; 
      ... 
     } 
     public int[] getArrayData(){ 
     return array1; 
     } 
} 

private class ButtonListener implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      StringBuffer dataSorted = new StringBuffer(""); 

      LoadListener loadListener = new LoadListener(); 

      // TODO: Get the list from the TextArea 
      int[] toSort = loadListener.getArrayData(); 
     } 
}