wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Array out of bounds Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Array out of bounds" Watch "Array out of bounds" New topic
Author

Array out of bounds

Karine Roy
Greenhorn

Joined: Jul 11, 2011
Posts: 13
I am new at Java and I am not sure if I am posting at the right place. Please let me know if I am not. I am trying to transfer a 2 dimension array to a text file but get the following runtime error:

java.lang.ArrayIndexOutOfBoundsException: 2
at Parts.writeArray(Parts.java:25)
at Parts.main(Parts.java:13)

Here is the code I have so far:

import java.util.Scanner;
import java.io.*;

public class Parts
{

static final String [][] parts = {{"1", "17.56"}, {"2", "18.56"}, {"3", "3.45"}, {"4", "0.67"}};

public static void main (String[] args) throws IOException
{

PrintWriter outputFile = new PrintWriter("Parts.txt");
writeArray(parts, "Parts.txt");}

public static void writeArray(String[][] parts, String outputFile)
{
PrintStream array;
try
{
array = new PrintStream(new FileOutputStream("Parts.txt"));
for (int row = 0; row < parts.length; row++)
{
for (int col = 0; col < parts.length; col++)
{
String s = parts[row][col];
array.println(s);
}
}
array.close();
}catch (FileNotFoundException e)
{
System.out.println("not found");}
}

}

Can someone please help me?

Thanks!
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

Your problem is that you have a 4 x 2 array, but your loop is going up to 4 x 4. If you use the lineit should work.

Also, please enclose your code in code tags so that it is readable.
Karine Roy
Greenhorn

Joined: Jul 11, 2011
Posts: 13
That was simple. Thank you so much! I will use the code tag next time.
Luigi Plinge
Ranch Hand

Joined: Jan 06, 2011
Posts: 441

You can also simplify this to thisso that you can't run into this problem.
Kammaganti Kamal
Greenhorn

Joined: Jul 12, 2011
Posts: 6
Hi Roy ,

The for loop of your code indicates the problem . you may replace it with the below mentioned code

 
Consider Paul's rocket mass heater.
 
subject: Array out of bounds
 
Similar Threads
Array out of bounds
Datatype casting. Split Strings to double 2D array. (loss of precision)
is it possible to change jvm locale by using command line parameters ?
Arrays with files
Write a method that can be called, that will initialize the seating plan.