Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: File to Array

  1. #1
    New to the CF scene
    Join Date
    May 2007
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    File to Array

    Hi!

    I want to read a file and save numbers to array . I saved numbers in array but this array is only available in try{}. How can I make it available also in main method?

    Thanks.


    Code:
    public static void main(String[] args) 
    	{
    		int[][]matrix;      //I want to save array in new array matrix
    		matrix = getArray();  
            }
    
    public static int[][] getArray()  
    {
      
        File file = new File ("numbers.txt");
        Scanner s = null;
        
        try 
        {
       
           s = new Scanner (file);
           int[][] array=new int[10][10]; 
                    
    	for (int i=0;i<array.length;++i)
    		for (int j=0;j<array[i].length;++j)
    			array[i][j]= s.nextInt();   //how can i make this array reachable in main method???
          }
          catch (Exception e)
          {
              System.out.println(e);
          }
          
      }

  • #2
    Senior Coder TheShaner's Avatar
    Join Date
    Sep 2005
    Location
    Orlando, FL
    Posts
    1,126
    Thanks
    2
    Thanked 40 Times in 40 Posts
    Code:
    public class yourprogram
    {
      public static void main(String[] args) 
      {
        int[][] matrix;
        matrix = getArray();  
      }
    
      public static int[][] getArray()  
      {
        File file = new File ("numbers.txt");
        Scanner s = null;
        
        try 
        {
          s = new Scanner (file);
          int[][] array=new int[10][10]; 
                    
          for (int i=0;i<array.length;++i)
            for (int j=0;j<array[i].length;++j)
              array[i][j]= s.nextInt();
    
          return array; // All you have to do is return the array back
        }
        catch (Exception e)
        {
            System.out.println(e);
            return 0;
        }
      }
    }
    -
    Shane

  • #3
    New to the CF scene
    Join Date
    May 2007
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks a lot.... I did tried that already but i forgot to put a return in catch{}

    Works now...


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •