Reputation:
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
Reputation: 5246
There are multiple issues.
int[][] posA=new int[A.length][A[0].length];
for(int j=0;j<A[0].length;j++) {
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