We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Loading integer arrays from text files
Page Index Toggle Pages: 1
Loading integer arrays from text files (Read 575 times)
Loading integer arrays from text files
Jul 2nd, 2009, 10:36pm
 
I am trying to load an array from a tex file. The text file has as many lines as the array I must load has rows, and each line has as many characters as the array has columns. I won't have trouble with values higher than 9 because there are none in the text file.

The way I figured out to do it is by loading the file into a String array, then trying to convert that string, one-dimensional array into an integer two-dimensional array. This way:

Code:

String [] fase;

int [][] blocks;

int [][] blocks = new int [8][8];
 String [] fase = loadStrings("fase.txt");
 
 for (int i = 0; i< 8; i++){
   for (int j = 0; j< 8; j++){
      blocks[i][j] = int(fase[i].charAt(j));
   }
 }


then I tried printing the values with:
Code:

 println(blocks[0][0]);
 println(blocks[7][7]);

wich should be 0 and then 3, but I got 48 and 51.

the text file is exactly this:
Code:
00111100
00100100
00100100
00100100
00100100
00100100
00111100
33333333


what is going wrong?
Re: Loading integer arrays from text files
Reply #1 - Jul 2nd, 2009, 10:59pm
 
int(charAt()) returns the Ascii code of the character, that's 48 for 0 and 51 for 3.
Just subtract 48 from the gotten value to have the numerical value (an old trick from C times..).
Re: Loading integer arrays from text files
Reply #2 - Jul 3rd, 2009, 4:39am
 
the weird thing is that the code:
Code:

 String number = "3";
 int deriv = int(number);
 println(deriv);

returns 3.

But thanks.
Re: Loading integer arrays from text files
Reply #3 - Jul 3rd, 2009, 4:56am
 
That's because you feed int() with a String, while charAt() returns a char... Actually, you are not calling the same function!
Try:
Code:
char number = '3';
int deriv = int(number);
println(deriv);
Re: Loading integer arrays from text files
Reply #4 - Jul 3rd, 2009, 5:39am
 
yeah, that kinda makes sense

another thing

is there a way to read the "data" folder, so I can, for example, load a specific file that the user of the processing application will choose?

a way to read the number of files and their names?
Re: Loading integer arrays from text files
Reply #5 - Jul 3rd, 2009, 6:08am
 
The question have been raised recently: Scanning a directory for a given file extension

You can use dataPath("") to get a String path or dataFile("") to get directly the needed File object.
Page Index Toggle Pages: 1