I have the following code in which I made a class List which is my version of an array list, with a method called "displayList()" which prints in the console the content of the list. After that, in the main method I have a System.out.println command that was supposed to print a string on the next line after the content of the list (after the list.displayList() invocation). Yet, the System.out.println command prints the string on the same line.
Here is my code:
public class List {
int [] initialArray = new int[10];
int cursor = 0;
public int [] add(int x) {
if(cursor == initialArray.length) {
int [] temp = new int [initialArray.length 10];
for (int i = 0; i < initialArray.length; i ) {
temp[i] = initialArray[i];
}
initialArray = temp;
}
initialArray[cursor ] = x;
return initialArray;
}
public void displayList() {
for (int i = 0; i < initialArray.length; i ) {
System.out.print(initialArray[i]);
if(cursor - 1 > i) {
System.out.print(", ");
}else {
break;
}
}
}
public static void main(String[] args) {
List list = new List();
list.add(10);
list.add(20);
list.displayList();
System.out.println("Abracadabra");
}
}
The output of this is:
10, 20Abracadabra
I do not understand why the result of list.display() and Abracadabra are on the same line. What am I doing wrong?
Thanks!
CodePudding user response:
System.out.println(" Abracadabra");
prints a new line at the end of the output but doesn't starts with a new line so in displayList you should do something like this
public void displayList() {
for (int i = 0; i < initialArray.length; i ) {
System.out.print(initialArray[i]);
if(cursor - 1 > i) {
System.out.print(", ");
}else {
break;
}
}
System.out.println(); //< adds a new line after list output
}
CodePudding user response:
All is good U only need to add System.out.println in place of System.out.print inside display method.