Hi
So I am trying to do this Print Array Program for my teacher, and I have tested this code. It worked. I added another section, wanting to make it ragged and out of order rather than all in a neat line. If you try it, without the ragged part, or the last public static void , then you will find that it works. I add the last part of my two dimensional program, the ragged part, and I add the last public static void code at the bottom. Didn't work.
The reason the thing gave me was because of an illegal start of expression , and yeah. I couldn't find the issue, but maybe you could?
Any tips on how to fix this is welcomed. Here is the image of the error message and the code
public class ArrayPrinter {
public static void main(String[] args) {
int[] oneD = {658, 43, 523};
printArray(oneD);
int[] oneD2 = {537, 287, 98, 67, 765};
printArray(oneD2);
int[][] twoD = {{23, 234, 253},
{345, 48, 109},
{23, 376, 198},
{37, 197, 123}
};
printArray(twoD);
int[] twoD2 = {{6},
{234},
{81},
{234},
{1}
};
printArray(twoD2);
public static void printArray(int[] arr) {
System.out.print('[');
int size = arr.length;
for(int i = 0; i < size; i++) {
System.out.print(arr[i]);
if(i < size - 1) {
System.out.print(",");
}
}
System.out.println(']');
}
public static void printArray(int[][] arr) {
System.out.print('[');
int size = arr.length;
for(int i = 0; i < size; i++) {
printArray(arr[i]);
}
System.out.println(']');
}
public static void printArray(int[][] arr) {
System.out.print('[');
int size = arr.length;
for(int i = 0; i < size; i++) {
printArray(arr[i]);
}
System.out.println(']');
}
}```
This is all in Java, by the way
There are a number of things…
You’re missing a closing bracket for main
twoD2 is declared as int but the initialization looks to be int . Either change the declaration or remove the {} on each element.
You have two definitions of printArray with int
Try to make the code work, but the fixed code is below
Fixed Code
public class ArrayPrinter {
public static void main(String[] args) {
int[] oneD = {658, 43, 523};
printArray(oneD);
int[] oneD2 = {537, 287, 98, 67, 765};
printArray(oneD2);
int[][] twoD = {{23, 234, 253},
{345, 48, 109},
{23, 376, 198},
{37, 197, 123}
};
printArray(twoD);
int[] twoD2 = {6,
234,
81,
234,
1
};
printArray(twoD2);
}
public static void printArray(int[] arr) {
System.out.print('[');
int size = arr.length;
for(int i = 0; i < size; i++) {
System.out.print(arr[i]);
if(i < size - 1) {
System.out.print(",");
}
}
System.out.println(']');
}
public static void printArray(int[][] arr) {
System.out.print('[');
int size = arr.length;
for(int i = 0; i < size; i++) {
printArray(arr[i]);
}
}
}
2 Likes
system
Closed
July 22, 2022, 2:35am
5
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.