user13143457
user13143457

Reputation:

How to calculate the even numbers of a two-dimensional array and write them into a file?

I need to calculate even numbers from a two-dimensional array and write them into a file, I'm new to java and wrote this code, but it doesn’t work, please tell me what’s the matter and how to fix it

 static void ex6(int[][] A) throws IOException{
   FileWriter fw = new FileWriter("ParCol.txt");
   int[][] posA=new int[A.length][A[0].length];
    for(int i=0;i<A.length;i++) {

       for(int j=0;j<A[0].length;j++) {
           if(A[0][j] % 2 == 0) {
               posA[i][j]=A[i][j];

           }
       }
   }

   fw.write((A.length)+" "+A[0].length+"\n");
   for(int i=0;i<posA.length;i++) {
       for(int j=0;j<posA[0].length;j++) {
           fw.write(posA[i][j]+" ");
       }
       fw.write("\n");
   }}

Upvotes: 0

Views: 305

Answers (1)

Jason
Jason

Reputation: 5246

There are multiple issues.

  1. You're assuming that all arrays in this 2d array are all the same length as seen below.
int[][] posA=new int[A.length][A[0].length];
  1. You're only looping through the array found in the first index of the 2d array as seen below.
 for(int j=0;j<A[0].length;j++) {
  1. Wrap your FileWriter in a try-with-resources.

You need to loop through all of the arrays in this 2d array. You have not specified but I assume you want each on a new line based on existing code.

    static void ex6(int[][] array) throws IOException {
        try (FileWriter fw = new FileWriter("ParCol.txt")) {
            for (int i = 0; i < array.length; i++) {
                int[] iArray = array[i];

                for (int j = 0; j < iArray.length; j++) {
                    int value = iArray[j];

                    if (value % 2 == 0) {
                        fw.write(Integer.toString(value));
                        fw.write("\n");
                    }
                }
            }
        }
    }

Java 8 Solution

    static void j8(Path path, int[][] array) throws IOException {
        String content = Stream.of(array)
                .flatMapToInt(IntStream::of)
                .filter(value -> value % 2 == 0)
                .mapToObj(Integer::toString)
                .collect(Collectors.joining("\n"));

        Files.write(path, content.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING);
    }

Upvotes: 1

Related Questions