I've been learning Java from scratch and really love it but there is this little problem of mine here I can't wrap my head around it. The following code works, I've tested it and the point is when the user goes backward in the list, the last output should not be duplicated. And here comes my question: why is (!goingForward) points to .next and not the other way around?
public static void visit(LinkedList<String> linkedList) {
ListIterator<String> listIterator = linkedList.listIterator();
boolean quit = false;
boolean goingForward = true;
Scanner scanner = new Scanner(System.in);
if(linkedList.isEmpty()) {
System.out.println("No cities to visit");
} else {
printMenu();
}
while (!quit) {
int actions = scanner.nextInt();
scanner.nextLine();
switch (actions) {
case 0:
printMenu();
break;
case 1:
if(!goingForward) {
if(listIterator.hasNext()) {
listIterator.next();
}
goingForward = true;
}
if(listIterator.hasNext()) {
System.out.println("Now visiting: " + listIterator.next());
} else {
System.out.println("Reached the end of the list");
goingForward = false;
}
break;
case 2:
if(goingForward) {
if(listIterator.hasPrevious()) {
listIterator.previous();
}
goingForward = false;
}
if(listIterator.hasPrevious()) {
System.out.println("Now visiting: " + listIterator.previous());
} else {
System.out.println("We are at the start of the list");
goingForward = true;
}
break;
case 3:
System.out.println("Thanks for using the app");
quit = true;
break;
}
}
