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.
Related
Im using Java and mySql
I have already done my code to prompt user to enter a date in the format DDMMYY and then store the info into the database, however, when i enter a valid date such as 121221, it will say "invalid date, please re-enter" Im not sure whats the problem..
this is my validation class
public class Validation {
public static boolean isValidDate(String date) {
String day = date.substring(0,2);
String month = date.substring(2,4);
String year = date.substring(4,6);
int i = Integer.parseInt(day);
int j = Integer.parseInt(year);
int k = Integer.parseInt(month);
if (k%2 !=0 || k == 8 || k == 10 || k == 12) {
if(i<=0 || i>31) {
return false;
}
}else if (k == 2) {
if(i<=0 || i>28) {
return false;
}
}else if (k%2 == 0 || k == 9 || k == 11) {
if (i<=0 || i>30) {
return false;
}
}
if(j<22 || j>100) {
return false;
}
return true;
}
public boolean isValidTransactionId(int transactionId) {
return true;
}
}
my UI class
package view;
import java.util.*;
import java.text.*;
import controller.DBController;
import controller.Validation;
import model.Transaction;
import model.Member;
public class UserInterface {
DBController db;
Validation vd;
Scanner scan;
Random rand;
String date;
boolean invalid;
int menuChoice, memberChoice;
Transaction transaction;
public UserInterface()throws Exception{
db= new DBController();
scan = new Scanner(System.in);
rand = new Random();
transaction = new Transaction();
}
public void MainMenu()throws Exception {
System.out.println("Welcome to SuperFun Theme Park!");
do {
System.out.print("Main Menu\n");
System.out.println("1. New Ticket Transaction");
System.out.println("2. Modify a Ticket Transaction");
System.out.println("3. Delete a Ticket Transaction");
System.out.println("4. View Ticket Transactions");
System.out.println("5. Exit");
System.out.print("Enter a number (1-5): ");
menuChoice = scan.nextInt();
scan.nextLine();
switch(menuChoice) {
case 1: newTicket(); break;
case 2: modifyTicket(); break;
case 3: deleteTicket(); break;
case 4: viewAllTransactions(); break;
case 5: System.out.println("Thank you. Have a nice day!"); break;
default: System.out.println("Invalid input. Please re-enter.\n");break;
}
}while(menuChoice!=5);
}
public void dateInput()throws Exception{
do {
if(menuChoice ==1 ) {
System.out.print("Enter ticket date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}else if (menuChoice == 4) {
System.out.print("Enter start date (DDMMYY): ");
date = scan.nextLine();
transaction.setDate(date);
}
invalid = false;
if(!vd.isValidDate(date)) {
invalid = true;
}else
invalid = false;
}while(invalid);
}
public void displayMemberInfo()throws Exception{
String result[] = null;
System.out.printf("\n%s %17s %20s\n","Index","Name", "Phone Number");
result = db.retrieveMemberInfo();
for(String temp: result)
System.out.println(temp);
}
public void newTicket() throws Exception{
int member=0, numOfMemberTickets=0, transactionId =0;
int memberTicket=80, nonMemberTicket=100, total=0, num=0;
boolean full = false, repeat= false;
//auto generate transaction id //100-200
int upperbound = 200;
int lowerbound = 100;
do {
transactionId = rand.nextInt(upperbound - lowerbound)+ lowerbound;
transaction.setId(transactionId);
}while(db.idExists(transaction.getId()));
//display transaction id
System.out.println("\nTransaction Id: " + transaction.getId());
//prompt user to enter ticket date
//validation for date
do {
dateInput();
db.maximumTicket(transaction.getDate());
if(db.sum>=100) {
System.out.println("Tickets are fully booked for the day. Please re-enter date.\n");
full = true;
}else {
System.out.printf("Number of tickets left for %s are %d\n" , date, 100-db.sum);
full = false;
}
}while(full);
//ask for total number of tickets then ask for members tickets
do {
System.out.print("Enter number of ticket(s) wanted: ");
num = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(num);
if(transaction.getTicketNum() > 100-db.sum)
System.out.println("Number of ticket(s) wanted exceeded availability. Please re-enter. ");
}while(transaction.getTicketNum() > 100-db.sum);
//if member, must choose which member
//loop through member info for validation
do {
repeat=false;
do {
System.out.print("Are there ticket(s) for member(s)? (1-yes 2-no): ");
member = scan.nextInt();
scan.nextLine();
if(member !=1 && member !=2)
System.out.println("Invalid input. Please re-enter.");
}while(member !=1 && member !=2);
if(member==1) {
do {
System.out.print("Enter the number of member tickets: ");
numOfMemberTickets = scan.nextInt();
scan.nextLine();
if(numOfMemberTickets<=0)
System.out.println("Invalid number of tickets. Please re-enter.");
}while(numOfMemberTickets<=0);
//display member info table
displayMemberInfo();
for(int cnt=0; cnt<numOfMemberTickets; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
// if(db.memberExists(transaction.getId())) {
// System.out.println("Member are only allowed to purchase one ticket in a day. Please re-enter.");
// repeat = true;
// }else
db.insertNumber(memberChoice, transaction.getId());
}while(memberChoice<=0);
}
}
}while(repeat);
//calculate and display total price
total = (numOfMemberTickets * memberTicket) + (Math.abs((transaction.getTicketNum() - numOfMemberTickets)) * nonMemberTicket);
transaction.setTotal(total);
System.out.println("Total price: RM" + transaction.getTotal());
//save data into database
boolean success = db.insertInfo(transaction.getDate(), transaction.getId(), transaction.getTicketNum(), transaction.getTotal());
if(success)
System.out.println("Transaction record inserted successfully.\n");
else
System.out.println("Error in inserting record.\n");
}
public void modifyTicket() throws Exception{
int transactionId=0, newTicketNum=0, newNumOfMemberTicket=0, newTotal=0, change=0;
String newDate="";
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
transaction.setId(transactionId);
if(!db.idExists(transaction.getId()))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transaction.getId()));
//display details
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transaction.getId());
//user can edit date, number and members' phone number
System.out.print("\nEnter new ticket date: ");
newDate = scan.nextLine();
transaction.setDate(newDate);
System.out.print("Enter new number of tickets(including members' tickets): ");
newTicketNum = scan.nextInt();
scan.nextLine();
transaction.setTicketNum(newTicketNum);
System.out.print("Enter new number of member ticket(s): ");
newNumOfMemberTicket = scan.nextInt();
scan.nextLine();
System.out.print("Is there a change in member(s)? (1-yes 2-no): ");
change = scan.nextInt();
scan.nextLine();
if(change==1) {
displayMemberInfo();
for(int cnt=0; cnt<newNumOfMemberTicket; cnt++) {
do {
System.out.print("\nPlease enter index number of member: ");
memberChoice = scan.nextInt();
db.updateNumber(memberChoice, transactionId);
}while(memberChoice<=0);
}
}
//recalculate total price
newTotal = (newNumOfMemberTicket * 80) + (Math.abs(newTicketNum - newNumOfMemberTicket)* 100);
transaction.setTotal(newTotal);
//update database
boolean success = db.updateInfo(transaction.getDate(), transaction.getTicketNum(), transaction.getTotal(), transaction.getId());
if(success)
System.out.println("Information updated successfully.\n");
else
System.out.println("Error in updating information.\n");
}
public void deleteTicket()throws Exception{
int transactionId=0, choice =0;
//enter transaction id
do {
System.out.print("Enter transaction id: ");
transactionId = scan.nextInt();
scan.nextLine();
if(!db.idExists(transactionId))
System.out.println("Transaction id does not exists. Please re-enter.");
}while(!db.idExists(transactionId));
transaction.setId(transactionId);
//display all information of that transaction
System.out.printf("\n%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
db.displayRecord(transactionId);
//re-confirm whether to delete
do {
System.out.print("\nConfirm delete? (1-yes 2-no): ");
choice = scan.nextInt();
}while(choice !=1 && choice !=2);
//delete from database
if(choice == 1) {
boolean success = db.deleteInfo(transaction.getId());
if (success)
System.out.println("Transaction Info deleted successfully.\n");
else
System.out.println("Error in deleting transaction info.\n");
}else
System.out.println("Returning to main menu...\n");
}
public void viewAllTransactions() throws Exception{
String result[] = null;
String date2 ="", letter="";
//enter start date
dateInput();
switch(date.substring(2,4)) {
case "01": letter = "Jan"; break;
case "02": letter = "Feb"; break;
case "03": letter = "Mar"; break;
case "04": letter = "Apr"; break;
case "05": letter = "May"; break;
case "06": letter = "June"; break;
case "07": letter = "July"; break;
case "08": letter = "Aug"; break;
case "09": letter = "Sep"; break;
case "10": letter = "Oct"; break;
case "11": letter = "Nov"; break;
case "12": letter = "Dec"; break;
}
date2 = date.substring(0,2) + letter + "20" + date.substring(4,6);
//show all records from start date
//display error if no matching one
boolean success = db.matchingDate(transaction.getDate());
if(success) {
System.out.println("\nTransaction Report from " + date2);
System.out.printf("%-4s %20s %25s %20s\n","Ticket Date", "Transaction Id", "Number of Tickets", "Total Price");
result = db.retrieveAllInfo(date);
for(String temp: result)
System.out.println(temp);
}else
System.out.println("Error in finding date entered.");
System.out.println("\nReturning to main menu...\n");
}
}
transaction class
public void setDate(String date) {
if(Validation.isValidDate(date))
this.date = date;
else
System.out.println("Date is invalid. Please re-enter.");
}
Honestly, those if checks are kind of hard to look at. Try this:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class dateTime {
public static void main(String[] args) throws ParseException {
SimpleDateFormat datefr = new SimpleDateFormat("dd-MM-yy");
datefr.setTimeZone(TimeZone.getTimeZone("UTC"));
datefr.setLenient(false);
try {
Date date = datefr.parse("12-10-21");
System.out.println(true);
} catch (ParseException e) {
System.out.println(false);
System.out.println(e.getMessage());
}
}
}
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 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 );
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!");
}
}
}