My While loop is only executing once and it appears it moves back to the top to run through the loop again but only completes the System.out.println("Title"); and then moves on to execute the switch case. It appear that if I change the int pages = scanner.nextInt(); and the int pub = scanner.nextInt(); to int pages = Integer.valueOf(scanner.nextLine()); and int pub = Integer.valueOf(scanner.nextLine()); the loop works as expected. I was wondering if anyone could explain why that is?
Code:
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Book> bookList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
boolean flag = true;
while (flag) {
System.out.println("Title:");
String title = scanner.nextLine();
if (!title.isEmpty()) {
System.out.println("Pages:");
int pages = scanner.nextInt();
System.out.println("Publication year:");
int pub = scanner.nextInt();
Book info = new Book(title, pages, pub);
bookList.add(info);
} else if (title.isEmpty()) {
flag = false;
}
}
System.out.println("What informaiton will be printed?");
String choice = scanner.nextLine();
switch (choice) {
case "everything":
if (choice.equals("everything")) {
for (Book info : bookList) {
System.out.println(info.getTitle() + ", " + info.getPages() + " pages, " + info.getYear());
}
}
case "name": {
if (choice.equals("name")) {
for (Book infor : bookList) {
System.out.println(infor.getTitle());
}
}
}
}
}