Java
Putting it together
Combine all parts into a working app.
Combine with a menu
In the final lesson you combine all pieces in a menu. You read a choice with Scanner; 1 adds a book, 2 borrows one. Error handling is built into the menu.
System.out.print("Seç: ");
int choice = input.nextInt();
if (choice == 1) {
System.out.print("Başlık: ");
input.nextLine();
cat.addBook(input.nextLine());
} else if (choice == 2) {
try { cat.borrowBook(); }
catch (IllegalStateException e) {
System.out.println("Hata: " + e.getMessage());
}
}
After nextInt you clear the leftover line with nextLine; then you read the real title. This solves the nextInt/nextLine trap you learned earlier. The menu gathers all skills in one flow.
All pieces together
In this lesson the Book class, the Catalog class (addBook, borrowBook, throw) and the Scanner menu come together. The user adds a book and borrows one; all errors are caught.
The starting code includes the previous lessons' solutions; you only write the menu loop. This is the beginner-level final task: variables, conditionals, loops, collections, methods, exceptions and input/output all in one app.
Exercise Run the menu
Write the menu in main: ask with System.out.print("Seç: "), read the choice with nextInt(). If choice == 1, print("Başlık: "), clear the line with nextLine(), read the title with nextLine() again and call cat.addBook(...). If choice == 2, try { cat.borrowBook(); } and catch IllegalStateException to print Hata: . Finally print cat.books. The user will type 1 then Suç ve Ceza.
Show example solution
System.out.print("Seç: ");
int choice = input.nextInt();
if (choice == 1) {
System.out.print("Başlık: ");
input.nextLine();
cat.addBook(input.nextLine());
} else if (choice == 2) {
try { cat.borrowBook(); }
catch (IllegalStateException e) {
System.out.println("Hata: " + e.getMessage());
}
}
System.out.println(cat.books);
Test yourself
-
Match each menu choice to its action
- 1
- Add book
- 2
- Borrow
- Seç:
- Ask for input
- Hata:
- Error message
-
Create the Scanner
Scanner input = new Scanner(System.____);
Show answer
Scanner input = new Scanner(System.in);
-
What happens when 1 is selected in the menu?
- A book is borrowed
- An error is thrown
- The program closes
- A title is asked and added
Show answer
A title is asked and added — when 1 is selected, a title is asked, read with nextLine and added with addBook.
Next lesson: Beginner section exam