Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 05-08-2007, 08:47 PM   PM User | #1
zacetnik
New to the CF scene

 
Join Date: May 2007
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
zacetnik is an unknown quantity at this point
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);
      }
      
  }
zacetnik is offline   Reply With Quote
Old 05-08-2007, 09:50 PM   PM User | #2
TheShaner
Senior Coder

 
TheShaner's Avatar
 
Join Date: Sep 2005
Location: Orlando, FL
Posts: 1,125
Thanks: 2
Thanked 40 Times in 40 Posts
TheShaner will become famous soon enoughTheShaner will become famous soon enough
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
TheShaner is offline   Reply With Quote
Old 05-08-2007, 10:25 PM   PM User | #3
zacetnik
New to the CF scene

 
Join Date: May 2007
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
zacetnik is an unknown quantity at this point
Thanks a lot.... I did tried that already but i forgot to put a return in catch{}

Works now...
zacetnik is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 07:14 AM.


Advertisement
Log in to turn off these ads.