[Solved!] Writing and reading to/from a 2D array!
Greetings! Basically, I'm having troubles writing integer data into a 2D array. I'm also not sure if I'm writing it correctly to, though it seems right.
Now to the examples:
This is how I write to 1D array:
Code:
public static void write ()
{
try
{
DataOutput d = new DataOutputStream (new FileOutputStream ("save.txt"));
DataOutput f = new DataOutputStream (new FileOutputStream ("alreadySaved.txt"));
for (int i = 0 ; i < 55 ; i++)
{
d.writeInt (userBooksRated [i]);
f.writeBoolean (true);
}
catch (Exception e)
{
String msg = e.toString ();
System.out.println (msg);
}
c.print ("Saved");
System.exit (-0);
}
That's no problem...
Next, I write a 2D array, declared in the beginning of the program, to a file. I do that so I can create a database file to use in the future.
Here's how I do it:
Code:
public static void write ()
{
try
{
DataOutput g = new DataOutputStream (new FileOutputStream ("database.dat"));
for (int i = 0 ; i < storeRatings.length ; i++)
{
for (int j = 0 ; j < storeRatings [i].length ; j++)
{
g.writeInt (storeRatings [i] [j]);
}
}
}
catch (Exception e)
{
String msg = e.toString ();
System.out.println (msg);
}
c.print ("Saved");
System.exit (-0);
}
and finally, on the next program launch, I want to write the integers from the database file into the array. This is what I do:
Code:
public static void readDatabase ()
{
try
{
DataInput b = new DataInputStream (new FileInputStream ("database.dat"));
for (int i = 0 ; i < storeRatings.length ; i++)
{
for (int j = 0 ; j < storeRatings [i].length ; j++)
{
storeRatings [i] [j] = b.readInt ();
}
}
}
catch (Exception e)
{
String msg = e.toString ();
System.out.println (msg);
}
}
Finally, when one part of the program tries to use the array I get an error. :(
java.lang.ArrayIndexOutOfBoundsException: 55
at BookISP.calculate(BookISP.java:238)
at BookISP.getRatings(BookISP.java:230)
at BookISP.menu(BookISP.java:423)
at BookISP.main(BookISP.java:64)
and here's the part of the code that uses the 2D array:
Code:
public static void calculate ()
{
for (int i = 0 ; i < 86 ; i++)
{
matchBooks [i] = userBooksRated [0] * storeRatings [i] [0];
for (int j = 1 ; j < 55 ; j++)
{
matchBooks [i] += userBooksRated [j] * storeRatings [i] [j];
}
}
c.close ();
c = new Console ();
findSimilar ();
}
My question is - what am I doing wrong? Am I writing it to the file wrong? Am I reading it from the file wrong?
Thanks for reading!