I am working on a Java program that prints arrays to methods. I am working on this code right now and I have gotten up to step 3 just fine. Step 3 is what I don't understand. I am not sure if I am just having a brain fart but I just do not understand what to do for this one step.
Here are the directions:
1.) Start a program in a class named ArrayPrinter
. Ignore the main method for a moment.
2.) In your class, create a static method named printArray
with one parameter of type int[]
named arr
. Inside this method, do the following.
a. Keep all of your output on one line using System.out.print()
until directed to use println()
.
b. Display an opening square bracket character.
c. Loop through the array that was passed into the method. Display the values in the array. Add a comma and a space after every value except for the last one.
d. Using System.out.println()
, display a closing square bracket character.
- In your main method, create the following array. Pass the reference to this array to the
printArray
method, run your program and verify that it works as expected.
Here is my code:
public class ArrayPrinter {
public static void main(String[] args) {
printArray(int[] oneD = {5, 6, 7, 8};)
}
public static void printArray(int[] arr) {
int size = arr.length;
System.out.print("[");
for(int i=0;i< size; i++){
System.out.print(arr[i]);
if(i<size-1){
System.out.print(",");
}
}
System.out.println("]");
}
}