Package mylib:
Library class:
package mylib;
import java.util.*;
class Library {
public static void main(String[] args) {
boolean isInfinite = true;
int book_index;
Scanner input = new Scanner(System.in);
Book[] myBooks = new Book[3]; // Create an array of books
// Initialize each element of the array
myBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
myBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
myBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);
do {
// Print book listing
System.out.println("\n***** BOOK LISTING *****");
for(int i = 0; i < myBooks.length; i++) {
Book book = myBooks[i];
System.out.println("[" + (i + 1) + "] " + book.sTitle + "\nAuthor: " +
book.sAuthor + "\nPages: " + book.iPages + "\nStatus: " + book.sStatus);
System.out.print("\r\n");
}
// Select library action
System.out.println("***** SELECT ACTION *****");
System.out.println("B - Borrow a book" + "\nR - Reserve a book" +
"\nI - Return a book" + "\nX - Exit program");
System.out.print("\nEnter command: ");
String sAction = input.nextLine();
try {
switch(sAction.toUpperCase()) { // Converts input to uppercase
// Borrow a book
case "B":
System.out.println("\n***** BORROW A BOOK *****");
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
myBooks[book_index-1].borrowBook(); // Call method from another class
break;
// Reserve a book
case "R":
System.out.println("\n***** RESERVE A BOOK *****");
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
myBooks[book_index-1].reserveBook(); // Call method from another class
break;
// Return a book
case "I":
System.out.println("\n***** RETURN A BOOK *****");
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
myBooks[book_index-1].returnBook(); // Call method from another class
break;
// Exit the program
case "X":
System.out.println("\nTerminating program...");
System.exit(0);
break;
default:
System.out.println("\nINVALID LIBRARY ACTION!");
break;
}
}
catch(ArrayIndexOutOfBoundsException err) {
System.out.println("\nINVALID BOOK INDEX!");
}
catch(InputMismatchException err) {
System.out.println("\nINVALID INPUT!");
}
} while(isInfinite);
}
}
Book class:
package mylib;
class Book {
int iPages;
String sTitle, sAuthor, sStatus;
public static final String AVAILABLE = "AVAILABLE",
BORROWED = "BORROWED", RESERVED = "RESERVED";
// Constructor
public Book(String sTitle, String sAuthor, int iPages) {
this.sTitle = sTitle;
this.sAuthor = sAuthor;
this.iPages = iPages;
this.sStatus = Book.AVAILABLE; // Initializes book status to AVAILABLE
}
// Constructor accepts no arguments
public Book() {
}
// Borrow book method
void borrowBook() {
if(sStatus.equals(Book.AVAILABLE) || sStatus.equals(Book.RESERVED)) {
sStatus = Book.BORROWED;
System.out.println("\nBORROW SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Reserve book method
void reserveBook() {
if(sStatus.equals(Book.AVAILABLE)) {
sStatus = Book.RESERVED;
System.out.println("\nRESERVE SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Return book method
void returnBook() {
if(sStatus.equals(Book.AVAILABLE)) {
System.out.println("\nBOOK IS ALREADY AVAILABLE!");
}
else if(sStatus.equals(Book.RESERVED)) {
System.out.println("\nBOOK IS ALREADY RESERVED!");
}
else {
sStatus = Book.AVAILABLE;
}
}
}
When I enter an invalid book index, say 4, the error is caught and it prints "INVALID BOOK INDEX!"
However, when I enter a char or string for the book index, it prints "INVALID LIBRARY ACTION!" when it should be printing "INVALID INPUT!"
The default clause appears to override the catch?
Your sAction variable is always a String, since Scanner.nextLine() returns String.
Therefore, your default statement is triggered, and it's reasonable to assume the InputMismatchException catch will never execute.
See also the other Scanner "next" methods if you'd like to fine-tune your input acceptance.
Example:
while (true) { // your infinite loop - better use a while-do instead of a do-while here
String sAction = input.nextLine(); // we assign sAction iteratively until user "quits"
// No try-catch: ArrayIndexOutOfBoundsException is unchecked and you shouldn't catch it.
// If it bugs, fix the code.
// No InputMismatchException either, as you don't need it if you use nextLine
// your switch same as before
}
Since the try-catch is for the int book_chosen and not for the String sAction, removing any of the catch-statement throws either OutOfBounds or InputMismatch error when I enter an int greater than 3 (OutOfBounds) or a char/string (InputMismatch) for the int book_chosen (Enter book index: ).
I have observed it is catching the errors when both catch statements are present, but not displaying the appropriate message. Since all are "invalid" inputs anyway, I found my way around it by just changing all the error prompts to INVALID INPUT!
Library class:
package mylib;
import java.util.*;
class Library {
static int book_index;
static Scanner input = new Scanner(System.in);
static void getIndex() {
System.out.print("Enter book index: ");
book_index = input.nextInt();
input.nextLine();
}
public static void main(String[] args) {
// Create an array of books
Book[] myBooks = new Book[3];
// Initialize each element of the array
myBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
myBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
myBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);
while(true) {
// Print book listing
System.out.println("\n***** BOOK LISTING *****");
for(int i = 0; i < myBooks.length; i++) {
Book book = myBooks[i];
System.out.println("[" + (i + 1) + "] " + book.sTitle +
"\nAuthor: " + book.sAuthor + "\nPages: " +
book.iPages + "\nStatus: " + book.sStatus);
System.out.print("\r\n");
}
// Select library action
System.out.println("***** SELECT ACTION *****");
System.out.println("B - Borrow a book" + "\nR - Reserve a book" +
"\nI - Return a book" + "\nX - Exit program");
System.out.print("\nEnter command: ");
String sAction = input.nextLine();
try {
switch(sAction.toUpperCase()) {
// Borrow a book
case "B":
System.out.println("\n***** BORROW A BOOK *****");
getIndex();
myBooks[book_index-1].borrowBook();
break;
// Reserve a book
case "R":
System.out.println("\n***** RESERVE A BOOK *****");
getIndex();
myBooks[book_index-1].reserveBook();
break;
// Return a book
case "I":
System.out.println("\n***** RETURN A BOOK *****");
getIndex();
myBooks[book_index-1].returnBook();
break;
// Exit the program
case "X":
System.out.println("\nTerminating program...");
System.exit(0);
break;
default:
System.out.println("\nINVALID INPUT!");
break;
}
}
catch(ArrayIndexOutOfBoundsException err) {
System.out.println("\nINVALID INPUT!");
}
catch(InputMismatchException err) {
System.out.println("\nINVALID INPUT!");
}
}
}
}
Book class:
package mylib;
class Book {
int iPages;
String sTitle, sAuthor, sStatus;
public static final String AVAILABLE = "AVAILABLE",
BORROWED = "BORROWED", RESERVED = "RESERVED";
// Constructor
public Book(String sTitle, String sAuthor, int iPages) {
this.sTitle = sTitle;
this.sAuthor = sAuthor;
this.iPages = iPages;
this.sStatus = Book.AVAILABLE;
}
// Constructor accepts no arguments
public Book() {
}
// Borrow book method
void borrowBook() {
if(sStatus.equals(Book.AVAILABLE) || sStatus.equals(Book.RESERVED)) {
sStatus = Book.BORROWED;
System.out.println("\nBORROW SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Reserve book method
void reserveBook() {
if(sStatus.equals(Book.AVAILABLE)) {
sStatus = Book.RESERVED;
System.out.println("\nRESERVE SUCCESSFUL!");
}
else {
System.out.println("\nBOOK IS UNAVAILABLE!");
}
}
// Return book method
void returnBook() {
if(sStatus.equals(Book.AVAILABLE)) {
System.out.println("\nBOOK IS AVAILABLE!");
}
else if(sStatus.equals(Book.RESERVED)) {
System.out.println("\nBOOK IS RESERVED!");
}
else {
sStatus = Book.AVAILABLE;
System.out.println("\nRETURN SUCCESSFUL!");
}
}
}
Related
I'm building a university management system where admin can log in, add student, department, 2ndly there is a faculty panel and lastly, there is a student panel where they can set course. But I've been facing some problems after adding a new student through the admin panel. The problem is if want to exit from the admin panel the whole program close. Is there any solution that if I exit from admin panel I should get back to main menu where i can enter in any panel again. there is one more problem if i tried to remove a student from registered it shows not found. Can anyone help me through this problem?
Here is my code MainActivity.java
import java.util.Scanner;
import mainpanel.*;
import interfacepart.*;
//import transactionpart.*;
public class MainActivity{
public static void main(String args[]){
boolean flag = true;
Student[] student1 = new Student[2000];
Scanner sc = new Scanner(System.in);
Admin a = new Admin("Admin", "1234");
System.out.println("**********Welcome to University Management*******");
//do {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Adming Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int choose = sc.nextInt();
sc.nextLine();
if(choose == 1){
Scanner ac = new Scanner(System.in);
System.out.println("**********Welcome to Admin panel*******");
System.out.println("Please enter the userName: ");
String user = sc.nextLine();
System.out.println("Please enter the password: ");
String password = sc.nextLine();
if("Admin".equals(user) && "1234".equals(password)){
do{
System.out.println("Login successful");
System.out.println ( "**** 1. add students and department *****");
System.out.println ( "**** 2. remove students *****");
System.out.println ( "**** 3. student Information *****");
//System.out.println ( "**** n 5, print student *****");
System.out.println ( "**** 4, exit the system *****");
int sel = sc.nextInt();
switch (sel){
case 1:
System.out.println("Enter the number of student you want to add: ");
int num = sc.nextInt();
sc.nextLine();
for (int i = 0; i<num; i++) {
if (student1[i] == null) {
System.out.println("Enter the deptname: ");
String depntName = sc.nextLine();
System.out.println("Enter the deptId: ");
String depntId = sc.nextLine();
System.out.println("Enter the totalCredit: ");
int totalCredit = sc.nextInt();
sc.nextLine();
Department cs = new Department(depntName, depntId, totalCredit);
Scanner mc = new Scanner(System.in);
System.out.println("Enter the StudentName: ");
String StudentName = mc.nextLine();
System.out.println("Enter the StudentId: ");
String StudentId = mc.nextLine();
System.out.println("Enter the StudentAge: ");
String StudentAge = mc.nextLine();
System.out.println("Enter the email: ");
String email = mc.nextLine();
System.out.println("Enter the bloodGroup: ");
String bloodGroup = mc.nextLine();
System.out.println("Enter the phoneNumber: ");
String phoneNumber = mc.nextLine();
System.out.println("Enter the Address: ");
String Address = mc.nextLine();
mc.nextLine();
Student s1 = new Student(StudentName,StudentId,StudentAge,email,bloodGroup,phoneNumber,Address);
student1[i] = s1;
a.addNewRegister(student1[i]);
a.addNewDepartment(cs);
student1[i].SetAdmin(a);
student1[i].SetDeparment(cs);
cs.addNewRegister(student1[i]);
//break;
}
else{
System.out.println ( "Number of students in full");
break;
}
}
break;
case 2:
boolean isStudentRegistered = false;
System.out.println("Please Enter the Id you want to remove: ");
Scanner newCheck = new Scanner(System.in);
String stdId = newCheck.nextLine();
for(Student total : student1){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}if(!isStudentRegistered){
System.out.println("No student found");
}
break;
case 3:
for(int i=0; i<1; i++){
a.showRegisteredInfo();
break;
}
break;
case 4:
System.exit(0);
//flag = false;
//break;
//continue;
break;
default:
break;
}
}while (true);
} else {
//flag = true;
System.out.println ( "Login failed please re-enter:");
}
}
else if(choose == 3){
Scanner std = new Scanner(System.in);
System.out.println ( "Welcome to Student Panel*******");
System.out.println("Please enter the StudentId: ");
String userId = std.nextLine();
System.out.println("Please enter the password: ");
String password = std.nextLine();
do{
for(Student total : student1){
if(total != null){
if(total.getId() == userId){
System.out.println("*********Welcome to university Portal***");
//isStudentRegistered = true;
total.showInfo();
}else{
System.out.println("You are not registered yet");
}
}
}
}while(true);
}
else{
System.out.println ( "Login failed please re-enter:");
}
/*} while (true);
}*/
}
}
Admin.java
package mainpanel;
public class Admin{
protected String userName;
protected String passWord;
Student[] addNewStudent;
Department[] department;
Courses[] courses;
int totalRegisterCount;
int totalDepartmentCount;
int totalCourseCount;
public Admin(){
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public Admin(String userName, String passWord){
this.userName = userName;
this.passWord = passWord;
addNewStudent = new Student[200];
department = new Department[10];
courses = new Courses[200];
totalRegisterCount = 0;
totalDepartmentCount = 0;
totalCourseCount = 0;
}
public void SetUserName(String userName){
this.userName = userName;
}
public String GetUserName(){
return userName;
}
public void SetpassWord(String passWord){
this.userName = userName;
}
public String GetPassword(){
return passWord;
}
public void addNewRegister(Student NewStudent){
addNewStudent[totalRegisterCount++] = NewStudent;
}
//public void removeNewStudent(Student removeNewStudent){
//}
public void addNewDepartment(Department dept){
department[totalDepartmentCount++] = dept;
}
public void addNewCourse(Courses crs){
courses[totalCourseCount++] = crs;
}
public void showDepartmentInfo(){
for(int i=0; i<totalDepartmentCount; i++){
department[i].showInfo();
}
}
public void showRegisteredInfo(){
for(int i=0; i<totalRegisterCount; i++){
addNewStudent[i].showInfo();
//addNewStudent[i].AllCourseInfo();
}
}
public void searchStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total.showInfo();
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
/*
public void removeStudentInfo(String stdId){
//department[num].showInfo();
boolean isStudentRegistered = false;
for(Student total : addNewStudent){
if(total != null){
if(total.getId() == stdId){
System.out.println("student found");
isStudentRegistered = true;
total = null;
System.out.println("Student removed");
}
}
}
if(!isStudentRegistered){
System.out.println("No student found");
}
}
*/
}
//courses[num].showInfo();
/*public void showCourseInfo(){
for(int i=0; i<totalCourseCount; i++){
courses[i].showInfo();
}
}
*/
Approach 1 - Not recommended
You can either have a loop surrounding the core functionality of your application and break out of any internal loops to go back to the beginning of the core loop.
Approach 2 - Recommended
You could refrain from using a core loop and refactor your code such that each menu interaction is a separate function.
Each function would present the user with a specific menu and depending on the user's input another function would be called for the next menu. Generally speaking, you would not require any loops to keep the application running.
This would reduce the complexity and confusion of your code and make it much easier to expand the application with new features without needing to concern yourself with where to place code within the loop.
I recommend reading up on SOLID design principles to get an idea of how best to structure code. Here is an example article. This answer and example code is not meant to be a full representation of SOLID design and I would recommend that you strongly consider using interfaces and separate classes for each distinct part of the system and not having all the code in the MainActivity class.
An example of a function-based approach would be as follows.
I mainly focussed on the Main Menu and Admin Menu. The principle can be applied across the entire application.
Scanner sc = new Scanner(System.in);
private void displayMainMenu() {
System.out.println("**********Please Choose the task you want to perform****");
System.out.println("1.Admin Login");
System.out.println("2.Faculty Login");
System.out.println("3.Student Login");
int input = sc.nextInt();
sc.nextLine();
switch (input) {
case 1:
displayAdminLoginMenu();
break;
case 2:
displayFacultyLoginMenu();
break;
case 3:
displayStudentLoginMenu();
break;
default:
// Display the main menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayMainMenu();
break;
}
}
private void displayAdminLoginMenu() {
// Perform login operation here
// After successful login display admin options menu
displayAdminOptionsMenu();
}
private void displayFacultyLoginMenu() {
}
private void displayStudentLoginMenu() {
}
private void displayAdminOptionsMenu() {
System.out.println("**** 1. add students and department *****");
System.out.println("**** 2. remove students *****");
System.out.println("**** 3. student Information *****");
System.out.println("**** 4, return to main menu *****");
System.out.println("**** 5, exit the system *****");
int input = sc.nextInt();
switch (input) {
case 1:
// Call function for option 1.
break;
case 2:
// Call function for option 2.
break;
case 3:
// Call function for option 3.
break;
case 4:
displayMainMenu();
break;
case 5:
exitApplication();
break;
default:
// Display the admin menu again if no option was successful.
// Can also handle possible errors here with feedback to the user.
displayAdminOptionsMenu();
break;
}
}
private void exitApplication() {
System.exit(0);
}
These are not necessarily the only options available, but they are what I could think of at the moment.
I am making a code in which the program shows some options like insert Book, delete Book etc.
The program asks us to enter certain details about a book by Insert method.
Once I enter details it goes back and show the options again.
When I choose search method it asks me search by title or search by ISBN or search by author. I choose an option and program works perfectly.
I made a method updateBook. It works fine but when I search for my UPDATED INFORMATION it shows nothing.
How to resolve this problem?
import java.util.Scanner;
public class BookApplication {
static Book head, pointer;
static Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Welcome to Smart Book Store");
System.out.println("Please choose an option from the list below");
int choice = 0;
do {
System.out.println("1. Insert Book\n2. Delete Book\n3. Search Book\n4. Update Book\n5. View Book\n6. Exit");
choice = scan.nextInt();
try {
choice = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
switch (choice) {
case 1:
addBook();
break;
case 2:
case 3:
searchBook();
break;
case 4:
updateBook();
break;
case 5:
break;
case 6:
scan.close();
System.exit(0);
break;
default:
System.out.println("Please choose from 1 to 5");
break;
}
}
} while (true);
}
static void addBook() {
if (head == null) {
String details[] = enterDetails();
pointer = new Book(details[0], details[1], details[2]);
head = pointer;
pointer.next = null;
} else {
String details[] = enterDetails();
pointer.next = new Book(details[0], details[1], details[2]);
pointer = (Book) pointer.next;
}
}
static String[] enterDetails() {
String[] details = new String[4];
try {
String title;
String ISBN;
String authors;
System.out.println("Please enter Book title");
title = scan.nextLine();
System.out.println("Please enter ISBN of book");
ISBN = scan.nextLine();
System.out.println("Please enter book's Author(s)");
authors = scan.nextLine();
details[0] = title;
details[1] = ISBN;
details[2] = authors;
} catch (Exception e) {
e.printStackTrace();
}
return details;
}
private static void searchBook() {
System.out.println();
System.out.println("1. Search by TITLE");
System.out.println("2. Search by ISBN");
System.out.println("3. Search by AUTHOR");
int choice = 0;
choice: try {
choice = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println();
System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 3");
break choice;
}
switch (choice) {
case 1:
System.out.println("Please enter Title of BOOK");
String title = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("BOOK(S) IN THE SYSTEM ARE: ");
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.title.equals(title)) {
System.out.println(pointer.getBook());
}
pointer = (Book) pointer.next;
}
}
break;
case 2:
System.out.println("Please enter ISBN of BOOK");
String ISBN = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("BOOK(S) IN THE SYSTEM ARE: ");
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.ISBN.equals(ISBN)) {
System.out.println(pointer.getBook());
break;
}
pointer = (Book) pointer.next;
}
}
break;
case 3:
System.out.println("Please enter Author(s) of BOOK");
String authors = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("BOOK(S) IN THE SYSTEM ARE: ");
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.authors.contains(authors)) {
System.out.println(pointer.getBook());
break;
}
pointer = (Book) pointer.next;
}
}
break;
default:
System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 5");
}
}
static void updateBook() {
System.out.println();
System.out.println("1. Update TITLE");
System.out.println("2. Update ISBN");
System.out.println("3. Update AUTHOR");
int choice = 0;
choice: try {
choice = Integer.parseInt(scan.nextLine());
} catch (Exception e) {
System.out.println();
System.out.println("PLEASE ENTER VALUE BETWEEN 1 - 3");
break choice;
}
switch (choice) {
case 1:
System.out.println("Please update Title of BOOK");
String another1 = scan.nextLine();
if (head == null) {
System.out.println("Title not Updated !");
return;
} else {
System.out.println();
System.out.println("Your new title is: " + another1);
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.title.equals(another1)) {
System.out.println(pointer.getBook());
break;
}
pointer = (Book) pointer.next;
}
}
case 2:
System.out.println("Please update ISBN of BOOK");
String ISBN = scan.nextLine();
if (head == null) {
System.out.println("Isbn not updated !");
return;
} else {
System.out.println();
int aISBN = Integer.parseInt(ISBN.trim());
System.out.println("Your book's updated ISBN is: " + aISBN);
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.ISBN.equals(aISBN)) {
System.out.println(pointer.getBook());
break;
}
pointer = (Book) pointer.next;
}
}
case 3:
System.out.println("Please enter Author(s) of BOOK");
String upauthor1 = scan.nextLine();
if (head == null) {
System.out.println("List is EMPTY !");
return;
} else {
System.out.println();
System.out.println("Book's Updated author is: " + upauthor1);
System.out.println();
pointer = head;
while (pointer != null) {
if (pointer.authors.contains(upauthor1)) {
System.out.println(pointer.getBook());
break;
}
pointer = (Book) pointer.next;
}
break;
}
}
}
}
Here is my another class.
public class Book {
String authors;
final String ISBN;
final String title;
public Object next;
Book(String title, String ISBN, String authors) {
this.title = title;
this.authors = authors;
this.ISBN = ISBN ;
}
public String getBook() {
return "Book Title: " + this.title + "\n" + "Book ISBN: " + this.ISBN + "\n" + "Book Authors: " + this.authors + "\n" ;
}
}
That's because you dont save the new data. It's obvious because you can add a book and update it. If you search for the updated info, there is nothing, but if you search for the old versions (pre-update) there it is.
pointer = head;
while (pointer != null) {
if (pointer.title.equals(another1)) {
System.out.println(pointer.getBook());
break;
}
pointer = (Book) pointer.next;
}
You just go through the list and expect the change to be done.
You should first have to ask for book info, search if it exists and then ask for the new data.
I am trying to create a driver class using array list of objects and it requires me to :
Read the book title from the user
Read the book ISBN from the user
Read the book in stock quantity from the user
program should continue to read the book information from the user until all the entries from the user for all the fields are blank or zero.
program will store valid book objects into an ArrayList (only valid objects)
Your program will then print the list all the "valid" Books entered by the user in the reverse order in which the books were entered.
As the user is entering information, the program should give feedback such as reporting that an item has been added to the ArrayList, or reporting any errors found.
Books with invalid entries were not added to the ArrayList, therefore they will not be printed when the ArrayList is printed
Here is my current code so far for my driver: (I'm a bit newb at this so )
edited: with the answer given
Here is what I got now
import java.io.*;
import java.util.*;
public class Bookstore2{
public static void main(String arg[ ]) throws Exception{
Scanner sc = new Scanner(System.in);
int isbn=0;
int quantity = 0;
String title = "";
Book oneBook;
List<Book> bookList = new ArrayList<Book>(); //here
while(true){
System.out.print("Enter title: ");
title = sc.nextLine( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
sc = new Scanner(System.in);
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
sc = new Scanner(System.in);
sc = new Scanner(System.in);
System.out.println();
// WRITE YOUR VALIDATION CODE HERE
// Change condition according to your requirements.
if(isbn !=0 && quantity != 0 && title != null && title != "")
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
} //main method
} //class
error now averted but it's not utilizing both my exception and book class it seems like
Here is my class and my exception that will be running with the new driver class
-----Class
public class Book{
//instance variables
private String title = "";
private int isbn;
private int quantity;
public Book (String title, int isbn, int quantity)throws BookException{
//constructors
setTitle(title);
setIsbn(isbn);
setQuantity(quantity);
}
public String toString( ){ //toString Method
String s = "";
s = s + "Title: " + this.title + "\nISBN: " + this.isbn + "\nQuantity: " + this.quantity + "\n";
return s;
}
public String getTitle( ){
return this.title;
}
public int getisbn( ){
return this.isbn;
}
public int getquantity( ){
return this.quantity;
}
//mutator methods
public void setTitle(String newtitle )throws BookException{
if(newtitle.length()<1){
BookException be = new BookException( );
be.setMessage("Title cannot be blank");
throw be;
}
else{
this.title=newtitle;
}
}
public void setIsbn(int newisbn)throws BookException{
if (isbn <= 1000 || isbn >= 10000) {
this.isbn = newisbn;
}
else{
BookException be = new BookException( );
be.setMessage("ISBN should be between 1000 and 10000.");
throw be;
}
}
public void setQuantity(int newquantity)throws BookException{
if(newquantity>=0){
this.quantity = newquantity;
}
else{
BookException be = new BookException( );
be.setMessage("Quantity can't be a negative number.");
throw be;
}
}
}
------Exception Class
public class BookException extends Exception {
//instance variable
private String message = "";
public void setMessage(String newMessage) {
this.message = newMessage;
}
public String getMessage() {
return this.message;
}
}
First of all use: while(true) loop to iterate until user entered 0 for all the field.
while(true)
{
// Scanner Code i.e. read input from the user.
if(//check all the inputs)
{
//create a new book and insert it into array list
}
else
{
// If input is 0, break from the loop
}
}
Secondly, Never perform validation in your bean class. Create a separate class or method to validate the inputs. After, input validation only then create a new object.
Hope this will help you.
The correct code :
sc = new Scanner(System.in);
while(true){
System.out.print("Enter title: ");
title = sc.nextLine( );
System.out.println();
System.out.print("Enter isbn: ");
isbn = sc.nextInt( );
System.out.println();
System.out.print("Enter quantity: ");
quantity = sc.nextInt( );
System.out.println();
// WRITE YOUR VALIDATION CODE HERE
// Change condition according to your requirements.
if(isbn !=0 && quantity != 0 && title != null && title != "")
{
oneBook = new Book(title, isbn, quantity);
bookList.add(oneBook); //create a list in main
System.out.println("Book added in the list.");
}
else
{
System.out.println("Book not added");
break;
}
}
for(int i = bookList.size()-1; i >= 0; i--){
System.out.println(bookList.get(i));
}
You posted :
while(title != null || title.equals("0") || isbn != null || isbn != 0 || quantity
isbn is of int type i.e. primitive type how can we compare it with a null.
quantity is also of int type.
Default value of an int i.e. primitive type is 0. And, primitive type can never be compared with null.
Since there is so much confusion on the code, here is a complete solution to the task:
Bookstore.java:
public class Bookstore {
static final Scanner in = new Scanner(System.in);
static List<Book> books = new ArrayList<>();
public static void main(String arg[]) throws Exception {
while (true) {
// read book information
Book book = new Book();
System.out.print("Enter title: ");
book.title = in.nextLine();
System.out.println();
System.out.print("Enter ISBN: ");
book.isbn = readInt();
System.out.println();
System.out.print("Enter quantity: ");
book.quantity = readInt();
System.out.println();
// exit condition: "blank book" entered
if (book.title.isEmpty() && book.isbn == 0 && book.quantity == 0) {
System.out.println("Goodbye!");
break;
}
//validate and add book
try {
validateBook(book);
books.add(book);
System.out.println("Book successfully added to the list.");
} catch (IllegalStateException ex) {
System.err.println("Book is not valid: " + ex.getMessage());
continue;
}
// print book list
for (int i = books.size() - 1; i >= 0; i--) {
System.out.println(books.get(i));
System.out.println();
}
}
}
static int readInt() {
while (true) {
String input = in.nextLine();
if(input.isEmpty()) {
return 0;
}
try {
return Integer.parseInt(input);
} catch (NumberFormatException ex) {
System.err.println("Expected a valid integer: " + input);
}
}
}
static void validateBook(Book book) {
if (book.title == null || book.title.isEmpty()) {
throw new IllegalStateException("Book title must not be blank.");
}
if (book.isbn < 1000 || book.isbn > 10000) {
throw new IllegalStateException("Book ISBN must be between 1000 and 10000.");
}
if (book.quantity < 0) {
throw new IllegalStateException("Book quantity must be positive.");
}
}
}
Book.java:
public class Book {
public String title;
public int isbn;
public int quantity;
#Override
public String toString() {
return String.join("\n",
"Title: " + title,
"ISBN: " + isbn,
"Quantity: " + quantity
);
}
}
HI My prof said this about my code
Please Help me I do not get what he wanted me to do with my code
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
Please Help me I do not get what he wanted me to do with my code
This is an address book containing 3 classes and this is one of the class that i really had a problem with
import java.util.Scanner;
public class AddressBookApp {
private static Scanner dataReader;
private static AddressBook book;
// TODO Address Book App
public static void main(String[] args) {
book = new AddressBook(10);
dataReader = new Scanner(System.in);
boolean lContinue = true;
while (lContinue) {
switch (Character.toUpperCase(menu())) {
case '1': addBookEntry(); break;
case '2': deleteEntry(); break;
case '3': viewAllEntries(); break;
case '4': editEntry(); break;
case '5': searchEntryByName(); break;
case '6': searchEntryByRecord(); break;
case 'X':
lContinue = false;
break;
default:
System.out.println("\nInvalid Menu option");
}
}
System.out.println("\nEnd of program...");
}
public static char menu() {
char choice;
System.out.println("\nAddressBook Menu");
System.out.println("1. Add Entry");
System.out.println("2. Delete Entry");
System.out.println("3. View all Entries");
System.out.println("4. Update an Entry");
System.out.println("5. Search Entry By Name");
System.out.println("6. Search Entry By Record Number");
System.out.println("X. Exit Program");
System.out.print("\nSelect Menu Option: ");
choice = dataReader.nextLine().charAt(0);
return choice;
}
public static AddressBookEntry getEntryDetails(AddressBookEntry entry) {
if( entry == null ) {
entry = new AddressBookEntry();
}
System.out.print("\nName : "); entry.setName(dataReader.nextLine());
System.out.print("Address : "); entry.setAddress(dataReader.nextLine());
System.out.print("Phone No.: "); entry.setTelNo(dataReader.nextLine());
System.out.print("Email : "); entry.setEmailAdd(dataReader.nextLine());
return entry;
}
public static void addBookEntry() {
AddressBookEntry entry = getEntryDetails(null);
if( entry != null ) {
book.addAddressBookEntry(entry);
}
}
public static void editEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
// The following code (mark by "-")can be replace by getEntryDetails(AddressBookEntry entry)
// you can just pass "addent" to the method
// always try to reuse as much methods/codes as possible
getEntryDetails(AddressBookEntry)
- System.out.println("Name: " + addent.getName());
- System.out.println("Edit Name: ");
- String name = datainput.next();
- addent.setName(name);
- System.out.println("Edit Address: ");
- String address = datainput.next();
- addent.setAddress(address);
- System.out.println("Edit EmailAdd: ");
- String emailAdd = datainput.next();
- addent.setEmailAdd(emailAdd);
- System.out.println("Edit TelNo: ");
- String telNo = datainput.next();
- addent.setTelNo(telNo);
displayEntry(addent, recnumb);
// TODO: edit a single record entry
//System.out.println("\nUnder construction....");
}
public static void searchEntryByRecord() {
try {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number: ");
int recnumb = datainput.nextInt();
AddressBookEntry addent = new AddressBookEntry();
addent = book.findAddressBookEntryByRecordNo(recnumb);
System.out.println("Name: " + addent.getName());
System.out.println("Address:" + addent.getAddress());
} catch (Exception NullPointerException) {
// TODO Auto-generated catch block
return;
}
// TODO: search an entry using its record no.
// display "record not found" if such record does not exist.
// Display all its entry.
// Hint: use the method "findAddressBookEntryByRecordNo()"
// from the AddressBook class
//System.out.println("\nUnder construction....");
}
public static void deleteEntry() {
Scanner datainput = new Scanner(System.in);
System.out.println("Enter record number to delete: ");
int recnumb = datainput.nextInt();
if (book.deleteAddressBookEntry(recnumb)) {
System.out.println("Deleted successfully.");
} else {
System.out.println("Record not found");
}
}
// TODO: delete an entry using its record no.
// display "record not found" if such record does not exist.
// Hint: use the method "deleteAddressBookEntry()"
// from the AddressBook class
// display a single record
public static void displayEntry(AddressBookEntry entry, int recNo) {
System.out.println("\nRecord No. " + recNo);
System.out.println("Name : " + entry.getName());
System.out.println("Address : " + entry.getAddress());
System.out.println("Phone No.: " + entry.getTelNo());
System.out.println("Email : " + entry.getEmailAdd());
}
// Search all entries containing name search criteria
public static void searchEntryByName() {
System.out.print("\nSearch[Name]: ");
// ensure no extraneous space and search criteria all in lowercase
String name = dataReader.nextLine().trim().toLowerCase();
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
for( int i = 0; i < list.length; i++ ) {
// compare search criteria with every entry
if(list[i]!=null && list[i].getName().toLowerCase().contains(name)) {
displayEntry(list[i],i+1);
}
}
System.out.println("No more records follow...");
}
public static void viewAllEntries() {
int validRecords = 0;
// get a reference to the Addressbook list
AddressBookEntry[] list = book.getAllEntries();
if( list.length == 0) {
System.out.println("\nList empty...");
}
for( int i = 0; i < list.length; i++ ) {
if( list[i] != null ) {
displayEntry(list[i],++validRecords);
}
}
System.out.println("No more entries to follow...");
}
}
Remove all lines which start with "-" and use this instead:
getEntryDetails( addent );
I'm using try on my code and it says illegal start of type. I'm using switch statements but default: continue; do not agree with each other I keep getting continue outside of loop. With the else statement it says illegal start type. So what can I do about try, continue, and the else statement.
public class Menu {
private Inventory database;
private char menuItem;
private Scanner input;
private char mode;
int code;
public Menu(Inventory database)
{
this.database = database;
menuItem = 'N';
input = new Scanner(System.in);
}
public Menu(MyArrayList database)
{
this.database = database;
menuItem = 'A';
input = new Scanner(System.in);
}
private void showMenu()
{
if(code == 'A'){
System.out.println();
System.out.println("------------------");
System.out.println("Display Movies : D");
System.out.println("Add Movie : A");
System.out.println("Delete Movie : X");
System.out.println("Select Mode : M");
System.out.println("Exit : E");
System.out.println("------------------");
System.out.println();
System.out.print("Please make your selection: ");
}
else
{
System.out.println();
System.out.println("------------------");
System.out.println("Display Movies : D");
System.out.println("Rent a Movie : R");
System.out.println("Reserve a Movie: S");
System.out.println("Select Mode : M");
System.out.println("Exit : E");
System.out.println("------------------");
System.out.println();
System.out.print("Please make your selection: ");
}
}
private void rentMovie(int productID)
{
int index = database.getIndex(productID);
if( index == -1)
{
System.out.println("There is not such a code.");
}
else
{
if( database.getMovie(index).getIsRented())
{
System.out.println("You cannot rent " + database.getMovie(index).getTitle() + ". It is already rented.");
}
else
{
database.getMovie(index).setIsRented(true);
System.out.println("Please take your movie.");
}
}
}
private void reserveMovie(int productID)
{
int index = database.getIndex(productID);
if( index == -1)
{
System.out.println("There is not such a code.");
}
else
{
if( database.getMovie(index).getIsReserved() )
{
System.out.println("You cannot reserve " + database.getMovie(index).getTitle() + ". It is already reserved.");
}
else
{
if( database.getMovie(index).getIsRented())
{
database.getMovie(index).setIsReserved(true);
System.out.println( database.getMovie(index).getTitle() + " is reserved for you." );
}
else
{
System.out.println( database.getMovie(index).getTitle() + " is available. You can rent it if you like.");
}
}
}
}
try{
if(mode == 'A'){
switch(menuItem){
case 'N':
break;
case 'D':
database.print();
showMenu();
menuItem = input.next().charAt(0);
break;
case 'A':
String title;
System.out.println("Enter movie title, then press enter");//movie title,
title= input.nextLine();
System.out.println("Enter movie code, then press enter");//enter movie code,then press enter
code = Integer.parseInt(input.nextLine());
addMovie(title,code);
menuItem ='N';
break;
case 'X':
System.out.println("");
deleteMovie(code);
menuItem ='N';
break;
case 'M':
selectMode();
menuItem = 'N';
case 'E':
System.out.print("Program terminated.");
System.exit(0);
break;
default:
continue;
}
}
}
else
{
public void run(){
int code;
while(true)
{
switch(menuItem)
{
case 'N':
break;
case 'D':
database.print();
showMenu();
menuItem = input.next().charAt(0);
break;
case 'R':
System.out.print("Please enter product code:");
rentMovie( input.nextInt() );
showMenu();
menuItem = input.next().charAt(0);
break;
case 'S':
System.out.print("Please enter product code:");
reserveMovie( input.nextInt() );
showMenu();
menuItem = input.next().charAt(0);
break;
case 'E':
System.out.print("Program terminated.");
System.exit(0);
break;
default :
showMenu();
menuItem = input.next().charAt(0);
}
}
}
}
You've got else following your try block, and that makes no sense. no, just bad indentation.
Where's your catch block, or finally block? It makes no sense to just have try. Also, you can't just declare a function in the middle of that else block.
Basically, I recommend you re-study the "Java Syntax" chapter of whatever guide you're using, because this code is just all kinds of wrong.
A.. Few pointers..
First of all, your Try doesn't have a catch.
Your case statements lack {} blocks.
And you can't create a method within an else block.
Further to answer your Question: Illegal start of type means you haven't initiated the variable. For example "menuItem"
Edit: To further that, default should be break; not continue;
Edit2: And further your second switch contains a boolean as argument...
With your edit, now showing the issue.
Your Try starts outside of a method body.
reserveMovie is closed just before try starts, and as such is not valid.