簡體   English   中英

從方法訪問ArrayList有哪些不同的方法?

[英]What are the different ways of accessing an ArrayList from a method?

我正在編寫一些家庭作業程序,因此我需要盡可能使用功能性編程原理來進行Java處理。 這些是程序的重要位,該程序接收數字列表並打印偶數:

   public static void main( String args[ ] )
   {
      ArrayList<Double> listEven = new ArrayList<Double>();
      inputRecursion( );
      outputRecursion( );
   }

   public static void inputRecursion( )
   {
      Scanner in = new Scanner( System.in );
      if( in.hasNextDouble() )
      {
         if( (in.nextDouble() % 2) == 0 )
         {
            listEven.add( in.nextDouble() );
         }
         inputRecursion( );
      }
   }

   public static void outputRecursion( )
   {
      Iterator<Double> it = listEven.iterator();

      if( it.hasNext() )
      {
         System.out.println( it.next() );
         outputRecursion( );
      }
   }

這是一個正在進行的工作,但是我不必運行它並檢查邏輯,因為我仍然在行中遇到兩個編譯錯誤:

listEven.add( in.nextDouble() );
Iterator<Double> it = listEven.iterator();

這兩行拋出“找不到符號”,我知道這是因為ArrayList的聲明方式使main之外的方法無法訪問。 我對解決此問題的方式有一個大概的了解。 我了解setter和getter,並且從我的研究中看它們看起來很簡單,但是我認為這些是最后的資源,因為我正努力避免使用變量(我知道我的程序還有其他可變的東西;我正在工作在上面)以盡可能滿足練習的限制。 我也知道我可以將其設為公共靜態,但是這會導致出現15個以上的錯誤,從我的查找開始,它需要“初始化”,並且還涉及變量。

還有其他方法可以使這兩個方法訪問ArrayList嗎? 我對不涉及變量或迭代的方式特別感興趣。

聲明ArrayList為靜態,但在主要功能之外,如下所示:

   static ArrayList<Double> listEven = new ArrayList<Double>();

   public static void main( String args[ ] )
   {
      inputRecursion( );
      outputRecursion( );
   }

   public static void inputRecursion( )
   {
      Scanner in = new Scanner( System.in );
      if( in.hasNextDouble() )
      {
         if( (in.nextDouble() % 2) == 0 )
         {
            listEven.add( in.nextDouble() );
         }
         inputRecursion( );
      }
   }

   public static void outputRecursion( )
   {
      Iterator<Double> it = listEven.iterator();

      if( it.hasNext() )
      {
         System.out.println( it.next() );
         outputRecursion( );
      }
   }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM