• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Array out of bounds

 
Karine Roy
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That was simple. Thank you so much! I will use the code tag next time.
 
Luigi Plinge
Ranch Hand
Posts: 441
IntelliJ IDE Scala Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also simplify this to thisso that you can't run into this problem.
 
Kammaganti Kamal
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Roy ,

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

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic