push Data to stack - java

package michael.week.pkg5;
class Employee {
String Fname ;
String Lname;
String PhoneNum;
String Address;
void setFirst(String First){
Fname = First ;
}
void setlast(String Last){
Lname = Last ;
}
void setAddress (String address){
Address = address ;
}
void setPhone (String Phone){
PhoneNum = Phone ;
}
void display (){
System.out.println ("the Fist name is :"+ Fname + " , the last name is : " + Lname + " ,the address is : "+ Address+ " ,the phone is : "+ PhoneNum);
}
}
package michael.week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MichaelWeek5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Stck {
Employee stck [] = new Employee[10];
int x ;
void stck (){
x= -1 ;
}
Employee push (Employee item){
if (x == 9){
System.out.println ("Stack is full");
}else stck[++x] = item ;
return stck[x];
}
Employee pop (){
if (x <0){
System.out.println (" Stack underflow");
return stck [x];
}else
return stck[x++];
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
String info2 = null ;
Stck obj = new Stck();
Employee obj2 = new Employee ();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.stck ();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
System.out.println ("please enter Employee last name name :");
info = br.readLine();
System.out.println ("please enter Employee address :");
info = br.readLine();
System.out.println ("please enter Employee phone number :");
info = br.readLine();
}
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}
Greetings,
i am new to java and i am working on this program....... i need to know how can i push the data to the stck ?
note : the push's parameter is type employee, and Employee contains First , Last, Phone , and address. how i can push each of them ?
here is what i did , and my instructor refused it
package week.pkg5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Week5 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
class Employee {
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
void increment(){
x++;
}
void PushFirst(String First){
Fname[x] = First ;
}
void Pushlast(String Last){
Lname [x] = Last ;
}
void PushPhone (String Phone){
PhoneNum [x] = Phone ;
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
}
void PushAddress (String address){
Address [x] = address ;
}
void pop (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
System.out.println ("the Fist name is :"+ Fname [x]+ " , the last name is : " + Lname [x] + " ,the address is : "+ Address[x] + " ,the phone is : "+ PhoneNum[x]);
x--;
}
}
void display (){
if (x < 0){
System.out.println (" No Empolyee !");
}
else {
for (int q = 0 ; q <=x ; q++){
System.out.println ((q+1)+"- "+"the First name is :"+ Fname [q]+ " , the last name is : " + Lname [q] + " ,the address is : "+ Address[q] + " ,the phone is : "+ PhoneNum[q]);
}
}
}
}
InputStreamReader inp = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(inp);
Employee obj = new Employee();
int w = -1 ;
for (int r=1 ;r>0; ){
System.out.println("please enter add to add new employee");
System.out.println("please enter display to display all employees list");
System.out.println("please enter pop to pop the last added employee");
System.out.println("please enter exit to exit");
String choice = br.readLine();
if(choice.equals("add")){
System.out.println(w);
if (w >= 9){
System.out.println("you reached the maxmum number !");
continue ;
}
else {
w++;
obj.increment();
String info ;
System.out.println ("please enter Employee first name :");
info = br.readLine();
obj.PushFirst(info);
System.out.println ("please enter Employee last name name :");
info = br.readLine();
obj.Pushlast(info);
System.out.println ("please enter Employee address :");
info = br.readLine();
obj.PushAddress(info);
System.out.println ("please enter Employee phone number :");
info = br.readLine();
obj.PushPhone(info);}
} else if(choice.equals("display")){
obj.display();
} else if(choice.equals("pop")){
obj.pop();
w--;
}else if(choice.equals("exit"))
break ;
else {System.out.println (choice + " is wrong choice !") ;
}
}
}
}

You would need to create a stack of employees and then you can push the whole employee object on to the stack.
import java.util.Stack;
...
Employee emp = new Employee();
Stack<Employee> stack = new Stack<Employee>();
stack.push(emp);

after creating an object to the class say (here stck) which will hold the data by calling method ex shown below
class std
{
int id;
string name;
public:
void set_id(int i)
{
id=i;
}
void set_name(string n)
{
name = n;
}
void disp()
{
system.out.println("name"+name+" and id = "+id);
}
};
main()
{
std s = new std();
s.set_id(1);
s.set_name("sunmoon");
s.disp();
}
so here you can observe that s is considered as stack and we pushed one person details as like you can create array of object and push n number of person details.

You have several issues in how you've modeled the data.
Issue #1 (The biggest issue of all):
An Employee should not have any internal representation of the stack. Think objects in the real world. In your example, each Employee should have:
a first name
last name
address
phone number
So the member fields :
String [] Fname = new String [10];
String[] Lname= new String [10];
String[] PhoneNum= new String [10];
String[] Address = new String [10];
int x= -1 ;
do not belong. This leads us to...
Issue #2 : The way you've modeled the Stack only allows for a fixed number of entries - 10 in your case). This is not how a stack should work. Read up on what a Stack is if you are uncertain. You can model a Stack in Java using a LinkedList - or use the built in Stack that Java provides. If you decide to create your own version, the important operations that need to be created are:
push
pop
isEmpty
My advice is to start by modelling the employee and pratice by pushing and popping them off of a built in Stack from the JDK until you really understand the operations before you try to create your own.

Related

Linked List in java isn't printing all items

I have an assignment where I'm supposed to get a name and phone number and store it in a linked list. However, when I'm printing out the list of 3 contacts, only the first contact is being printed. What am I doing wrong?
This is the file that was given to me with the main.
ContactList.java
public class ContactList
{
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
String name;
String number;
ContactNode contact1;
ContactNode contact2;
ContactNode contact3;
System.out.println("Person 1");
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
number = scnr.nextLine();
System.out.println("You entered: " + name + ", " + number);
contact1 = new ContactNode(name, number);
System.out.println("Person 2");
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
number = scnr.nextLine();
System.out.println("You entered: " + name + ", " + number);
contact2 = new ContactNode(name, number);
System.out.println("Person 3");
System.out.println("Enter name:");
name = scnr.nextLine();
System.out.println("Enter phone number:");
number = scnr.nextLine();
System.out.println("You entered: " + name + ", " + number);
contact3 = new ContactNode(name, number);
ContactNode temp = contact1;
contact3.insertAfter(contact2);
contact2.insertAfter(contact1);
System.out.println("CONTACT LIST:");
while (temp!= null)
{
temp.printContactNode();
temp = temp.getNext();
System.out.println();
}
}
}
This is the file that I was to implement.
ContactNode.java
public class ContactNode
{
private String contactName;
private String contactPhoneNumber;
private ContactNode nextNodePtr;
// constructor
public ContactNode(String name, String num)
{
contactName = name;
contactPhoneNumber = num;
nextNodePtr = null;
}
public String getName()
{
return contactName;
}
public String getPhoneNumber()
{
return contactPhoneNumber;
}
public void insertAfter(ContactNode nodeLoc)
{
ContactNode tmpNext;
tmpNext = this.nextNodePtr;
this.nextNodePtr = nodeLoc;
nodeLoc = tmpNext;
}
public ContactNode getNext()
{
return this.nextNodePtr;
}
public void printContactNode()
{
do
{
System.out.println("Name: " + this.contactName);
System.out.println("Phone number: " + this.contactPhoneNumber);
this.getNext();
} while(getNext() != null);
}
}
In your do while loop, there isn't any logic to move onto the next contact. Calling this.getNext() won't accomplish anything if you're not referencing the result. What you're probably looking for is something like this:
ContactNode current = this;
do {
// Print
current = current.getNext();
} while(current != null);
To solve problems like this in the future, you should probably take a look at what your code is doing line by line. For example, say we have two contacts (contact 1 and contact 2). Then your code will print the first contact information, then retrieve contact 2 (with this.getNext()) but not do anything with it, then check whether getNext() (contact 2) is null, which it isn't. Then the loop will repeat and the same process will happen again. Your code is never moving on.

java.lang.NullPointerException when setting value of attributes within a loop

Trying to make it so if the user types "end", in the second input which is "Enter the first name of student", the loop automatically assigns each object in the array the attributes of "null" for id and name, and 0 for age and id, as well as breaking the outerloop. However, I get the error java.lang.NullPointerException.
Any help would be appreciated.
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
System.out.println("Enter number of students");
int numberof = myObj.nextInt();
System.out.println("Number of students is " + numberof);
Student Studentz[] = new Student[numberof];
outerloop:
for (int i = 0; i < numberof; ++i) {
Studentz[i] = new Student();
System.out.println("Enter first name of student " + (i + 1));
Scanner myObj1 = new Scanner(System.in);
String firstname = myObj1.nextLine();
System.out.println("Firstname is: " + firstname);
if (firstname.equals("end")) {
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null");
Studentz[g].Setlast("null");
Studentz[g].Setage(0);
Studentz[g].Setid(0);
}
break outerloop;
} else {
Studentz[i].Setfirst(firstname);
System.out.println("Enter last name of student " + (i + 1));
Scanner myObj2 = new Scanner(System.in);
String lastname = myObj2.nextLine();
System.out.println("Last name is: " + lastname);
Studentz[i].Setlast(lastname);;
System.out.println("Enter age of student " + (i + 1));
Scanner myObj3 = new Scanner(System.in);
int nazca = myObj3.nextInt();
System.out.println("Age is: " + nazca);
Studentz[i].Setage(nazca);
System.out.println("Enter ID of student " + (i + 1));
Scanner myObj4 = new Scanner(System.in);
int nazca1 = myObj4.nextInt();
System.out.println("ID is: " + nazca1);
Studentz[i].Setid(nazca1);
}
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
}
}
}
public class Student {
private String first;
private String last;
private int age;
private int id;
public int getid() {
return
this.id;
}
public void Studentss(String f, String l, int a, int i) {
first = f;
last = l;
age = a;
id = i;
}
public void Setfirst(String z) {
this.first = z;
}
public void Setlast(String za) {
this.last = za;
}
public void Setage(int zb) {
this.age = zb;
}
public void Setid(int zc) {
this.id = zc;
}
public String Snake() {
String snek = "Name is " + this.first + " " + this.last + " , Age is " + this.age + " ,ID is " + this.id;
return snek;
}
}
you fail here because you try to print students data before you initialized all elements of Studentz array:
for (int c = 0; c < numberof; ++c) {
System.out.println(Studentz[c].Snake());
}
also your code fails here by the same reason:
for (int g = i; g < numberof; ++g) {
Studentz[g].Setfirst("null"); // NPE - no Student created yet in the array
Some Possibly Helpful Tips:
Follow Java naming rules for your variables and method names, Studentz should be studentz, even for your Arrays. I know...your tired of reading that but as you progress, you'll see how beneficial it really is.
If you can, don't use multiple Scanner objects, there is no need for that in your use-case. Declare one Scanner object and stick with it. You're probably doing this because you are using the nextLine() method after the nextInt() method and you're finding that it skips the first name prompt and provides a Null String (""). This happens because the nextInt() method does not consume the newline character when the Enter key is hit. To solve this problem you would either, place the code line myObj.nextLine(); directly under the int numberof = myObj.nextInt(); code line:
int numberof = myObj.nextInt();
myObj.nextLine(); // Consume ENTER key hit
or don't use the nextInt() method at all. Instead just stick with the nextLine() method and not worry about consumption:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
It's always a good idea to validate any input from the User (as shown above), even if they're in a for loop. Give the User an opportunity to make a correct entry, after all, typo's do happen.
Get rid of the outerLoop: label. As a matter of fact, try avoid ever using them if you can....and you can. It would only be on a relatively rare occasion where you might ever need one.
Give your variables meaningful names, at least to some extent. This can benefit you later on down the road when you want to read your old code in the future.
In your Student class you made yourself a this real nice method named Studentss(). Well, I think it should be a constructor instead and save yourself a lot of code entry for calls to Setter methods. After all, that's mostly what the constructor is for. Your Student class constructor can look like this:
public Student(String firstName, String lastName, int age, int id) {
this.first = firstName;
this.last = lastName;
this.age = age;
this.id = id;
}
And be used like this. You will notice that upon each iteration of the outer for loop, all the prompt answers are placed within variables then at the end of all those prompts the constructor is used instantiate a student object, for example:
studentz[i] = new Student(firstname, lastname, age, id);
Doing it this way mean that there is no need to make calls to Setter methods. There is nothing wrong with making setter calls, it's just easier using the constructor. This is demonstrated below:
Scanner myObj = new Scanner(System.in);
int numberof = 0;
String val = "";
while (val.equals("")) {
System.out.println("Enter number of students");
val = myObj.nextLine();
if (!val.matches("\\d+")) {
System.err.println("Invalid number supplied!");
val = "";
continue;
}
numberof = Integer.parseInt(val);
}
System.out.println("Number of students is " + numberof);
Student[] studentz = new Student[numberof];
for (int i = 0; i < numberof; ++i) {
String firstname = "null";
String lastname = "null";
int age = 0;
int id = 0;
boolean exitOuterForLoop = false;
// Student First Name Prompt:
// (with option to End and default remaining to null's and 0's)
while (firstname.equals("null")) {
System.out.println("Enter first name of student " + (i + 1) + " (End to stop):");
firstname = myObj.nextLine();
if (firstname.equalsIgnoreCase("end")) {
firstname = "null";
//Make all remaining Student instances null and 0
for (int g = i; g < numberof; ++g) {
studentz[g] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
exitOuterForLoop = true;
break; // Exit this 'while' loop
}
// Validate first name (no numbers or crazy characters)
if (!firstname.matches("(?i)[a-z']+")) {
System.err.println("Invalid First Name! (" + firstname + ") Try Again...");
firstname = "null";
}
}
if (exitOuterForLoop) {
break; // Exit this outer 'for' loop.
}
System.out.println("Firstname is: " + firstname);
// Student Last Name Prompt
while (lastname.equals("null")) {
System.out.println("Enter last name of student " + (i + 1));
lastname = myObj.nextLine();
// Validate last name (no numbers or crazy characters)
if (!lastname.matches("(?i)[a-z']+")) {
System.err.println("Invalid Last Name! (" + lastname + ") Try Again...");
lastname = "null";
}
}
System.out.println("Last name is: " + lastname);
// Student Age Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter age of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid Age Supplied! (" + val + ") Try Again...");
val = "";
}
}
age = Integer.parseInt(val);
System.out.println("Student age is: " + age);
// Student ID Prompt
val = "";
while (val.equals("")) {
System.out.println("Enter ID of student " + (i + 1));
val = myObj.nextLine();
// Validate age (digits 0 to 9 only)
if (!val.matches("\\d+")) {
System.err.println("Invalid ID Supplied! (" + val + ") Try Again...");
val = "";
}
}
id = Integer.parseInt(val);
System.out.println("Student ID is: " + id);
studentz[i] = new Student(firstname, lastname, age, id); // Use Student class constructor
}
// Display the instances of Student contained within the 'studentz[]' array.
for (int c = 0; c < numberof; ++c) {
System.out.println(studentz[c].toString());
}
The snake() method is actually just another toString() method and there is nothing wrong with that however you might want to consider using StringBuilder class to create the returned string rather than doing concatenations, for example:
public String snake() {
return new StringBuilder("Name is ").append(this.first).append(" ").append(this.last)
.append(" , Age is ").append(this.age).append(" , ID is ")
.append(this.id).toString();
}
Not overly important here but it can save you memory if you do a lot concatenating with many large strings.

Cinema Queue Doesn't Work Java

I need to be able to verify an age in the main class so for example if the name and age is added to the queue and when the person tries to leave if the age is less than 18 then a message appears saying "left because too young" or if the person is over 18 then a message appears saying "person left"
This is my main Class
public static void main(String[] args)
{
Queue q = new Queue();
Scanner k = new Scanner(System.in);
System.out.print("Join (j), leave (l) or end (e)? ");
String action = k.nextLine();
while (!action.equalsIgnoreCase("e"))
{
if (action.equalsIgnoreCase("j"))
{
System.out.print("Enter Name ");
String Name = k.nextLine();
System.out.print("Enter Age : ");
int Age = k.nextInt();
Person p1 = new Person(Name,Age);
q.add(p1);
System.out.println(Name + " Age " + Age + " Joined");
}
else if (action.equalsIgnoreCase("l"))
{
if (!q.isEmpty())
{
System.out.println(q.remove() + " Person Left");
}
else
{
System.out.println("Queue Empty");
}
}
else
{
System.out.println("Invalid operation");
}
System.out.print("Join (j), leave (l) or end (e)? ");
action = k.nextLine();
I also have a person class with the name and age and also a Queue Class.
Why can't you just add an if statement?
int Age = k.nextInt();
Person p1 = new Person(Name, Age);
q.add(p1);
if (Age < 18) {
q.remove(p1);
System.out.println("left because too young");
}

Library Program - Assigning & checking out books

I'm supposed to create a library program in java that allows you to create patrons and check out a maximum of 3 books. I'm really beginner at java so I apologize that my code is all over the place and may not make sense.
Below is the library class that I attempted(i also have a separate Patron, Book and Book Interface class)
My main concerns:
I have 2 ArrayLists, one for a list of inputed Users and another for a list of inputed Books. However how would i be able to assign certain checked out books to a certain user & make sure they borrow no more than 3?
I put a lot of the code in the main method but i end up having a lot of problems with static and non static stuff
How would I be able to create status' for each book? for example if "great expectations" is checked out, how can assign "borrowed" to it and make sure no one else can borrow it?
The program runs so far but its lacking depth because I'm lost as to how to check out/in books under a certain specified patron.
SORRY again for all the inconsistencies in my code and i really really appreciate the help!
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
import java.util.Collections;
public class Library
{
static ArrayList <Patron> UserList = new ArrayList<Patron>();
static ArrayList <String> BookList = new ArrayList <String> ();
public static String status;
public static String borrower;
public static String borrowDate;
public static String returnDate;
public String status1 = "Available";
public String status2 = "Borrowed";
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("********************Welcome to the Public Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
while(choice != 9)
{
System.out.println("1: Add new patron");
System.out.println("2: Add new book");
System.out.println("3: Edit patron");
System.out.println("4: Edit book");
System.out.println("5: Display all patrons");
System.out.println("6: Display all books");
System.out.println("7: Check out book");
System.out.println("8: Check in book");
System.out.println("9: Search book");
System.out.println("10: Search Patron");
System.out.println("9: Exit");
choice = input.nextInt();
switch(choice)
{
case 1: //Add new patron
System.out.print("Enter patron first name: ");
String firstName = input.next(); //read name from input
System.out.print("Enter patron last name: ");
String lastName = input.next();
UserList.add(new Patron(firstName, lastName)); //add name to list
System.out.println("-----You have successfully added a new patron!-----");
break;
case 2: //Add new book
System.out.print("Enter book title: ");
String title1 = input.next();
Scanner input1 = new Scanner(System.in);
System.out.print("Enter book author: ");
String author1 = input.next();
Book book1 = new Book(title1);
BookList.add(title1);
FullBookList.add(fullBook);
System.out.println("-----You have successfully added a new book!-----");
status = "available";
borrowDate = "none";
returnDate = "none";
borrower = "none";
break;
case 3: //Edit patron name
System.out.println("Enter original patron name: ");
String originalName = input.next();
System.out.println("Enter edited patron name: ");
String editedName = input.next();
//Collections.replaceAll(UserList, originalName, editedName);
if(UserList.contains(originalName))
{
}
case 4: //edit book
case 5: //display all patrons
System.out.println(UserList);
break;
case 6: //display all books
System.out.println(BookList);
break;
case 7: //check out a book
Patron.CheckOutBook();
break;
case 8: //check in a book
Patron.CheckInBook();
break;
}
}
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class Patron
{
Scanner input = new Scanner(System.in);
private String first;
private String last;
int bookCount = 0; //amount books user has in pocket
int books = 0;
//constructor to "add new patron" by entering their name.
public Patron(String f, String l)
{
first = f;
last = l;
}
public String toString()
{
return first + " " + last;
}
public String getName()
{
return first + " " + last;
}
public static void CheckOutBook()
{
System.out.println("Enter book title to be check out: ");
Scanner input = new Scanner(System.in);
String bookCheckOut = input.next();
if(Library.BookList.contains(bookCheckOut))
{
Library.BookList.remove(bookCheckOut);
System.out.println("-----" + bookCheckOut + " has been checked out!-----");
System.out.println ("-------" + bookCheckOut + " is due in 7 days!-------");
}
else
System.out.println(bookCheckOut + " is not in the library. Please enter "
+ "a different book to be checked out");
}
public static void CheckInBook()
{
System.out.println("Enter book title to be checked in: ");
Scanner input = new Scanner(System.in);
String bookCheckIn = input.next();
if(Library.BookList.contains(bookCheckIn))
{
Library.BookList.add(bookCheckIn);
System.out.println("-----" + bookCheckIn + " has been checked in!-----");
}
else
System.out.println(bookCheckIn + " is not in the library. Please enter "
+ "a different book to be checked out");
}
public boolean canBorrow()
{
if(bookCount <= 3)
{
return true;
}
else
{
return false;
}
}
}
Note: This will likely involve some refactoring to your main loop.
Alright so the way I see it, we have three classes at play here: some Patrons, which can check books out and in, some Books, which have statuses like "available" and "checked out," and a Library, which contains books. So, we need 3 classes:
I'll start with Book and use pseudo code to explain the concepts for you to implement.
class Book
{
//private fields
private final String title;
private final String author;
private Status available = true;
//note--i would prefer using an Enum called status for this,
//but a boolean true/false value works adequately
//Constructor
public Book(string title, string author) {}
//accessors for title, author, available
//setter for available--used for Library only--there are better ways to ensure
//Patrons can't set the status of the book, but for now this is the simplest way
}
As you can see, Books have immutable fields that don't need to change, and one field that tracks it status. A better implementation might make Library track book status, as that makes more logical sense and better code, but this a simple implementation.
Next, Library, which needs lots of books:
class Library
{
private final ArrayList<Book> books;
//Constructor
public Library ()
{
books = loadBooks();
}
//some methods
private ArrayList<Book> loadBooks () {}
//however you want to create all your books (file input, whatever)
public bool isBookAvailable (Book b)
{
if b isn't in library: return false
else return (b in books).isAvailable()
}
public Book checkoutBook (Book b)
{ get book (checking availability, possibly returning a null Book), set status to unavailable, return it }
public Book checkinBook (Book b)
{ check that this the book belongs to library, set status to available }
}
As I said earlier, this isn't perfect. I could spend quite some time going on and on about how to improve the design, but for the sake of simplicity won't.
Now, Patrons. One question is, should Patrons have only one library that the visit? Or do they visit multiple libraries? I'll assume they visit more than one, since sometimes a library doesn't have all the books you want.
class Patron
{
private final String name;
private final Book[] books = new Book[3];//you can see I'm limiting them to 3 books
private int index = 0;
//Constructor
public Patron (String name) {}
//methods
public void checkoutBook (Book b, Library l)
{//could be tricky
check books status in l (l.isBookAvailable(b))
if available:
if space (index < 2) Book newBook = l.checkoutBook(b); books[index++] = newBook;
else: no space
else: not available
}
public void checkinBook (int bookIndex, Library l)
{
if bookIndex < 3:
if books[index] != null:
l.checkinBook (books[index]);
books[index--] = null;
else: no book
else: not valid index
}
}
Of course, other utilities like displaying books (library, patron) and toString methods might be useful. But now the responsibility of the main method is to create some patrons, a library, and give patrons the chance to check out and check in books via a menu. You have the heavy lifting done; you can work on input and output now.
Any questions?
A Beginner Level "Student Library Program" in JAVA, which interacts the Students and the Books. This Library Program can do following functions:
1-Adding a Book to Library.
2-Update Book Quantity.
3-Search a Book with its Serial number.
4-Search Books With Author Name.
5-Show all Books and their related Information.
6-Registering a Student.
7-Show All Registered Students.
8-Student can Check Out Book From Library(if registered).
:- Student can not Check Out more than 3 Books
:- You can only borrow a Book If it is Available in Library
9-Student can Check In Book to Library.
10-You can also see the Books which a Student has Checked Out(only while checking in)
Note: At the time it can store only 50 books for simlicity in program
I Have created this program with the maximum skill and knowledge i had in java. As I'm a Beginner so I couldn't do more
Kindly give reviews about Program
Also tell me refinements which are to be made in program
Kindly Tell me the better way to do this Program
package library;
import java.util.Scanner;
public class book {
public int sNo;
public String bookName;
public String authorName;
public int bookQty;
public int bookQtyCopy;
Scanner input = new Scanner(System.in);
public book(){
System.out.println("Enter Serial No of Book:");
this.sNo = input.nextInt();
input.nextLine();
System.out.println("Enter Book Name:");
this.bookName = input.nextLine();
System.out.println("Enter Author Name:");
this.authorName = input.nextLine();
System.out.println("Enter Quantity of Books:");
this.bookQty = input.nextInt();
bookQtyCopy = this.bookQty;
}
}
package library;
import java.util.Scanner;
public class books {
book theBooks[] = new book[50]; // Array that stores 'book' Objects.
public static int count; // Counter for No of book objects Added in Array.
Scanner input = new Scanner(System.in);
public int compareBookObjects(book b1, book b2){
if (b1.bookName.equalsIgnoreCase(b2.bookName)){
System.out.println("Book of this Name Already Exists.");
return 0;
}
if (b1.sNo==b2.sNo){
System.out.println("Book of this Serial No Already Exists.");
return 0;
}
return 1;
}
public void addBook(book b){
for (int i=0; i<count; i++){
if (this.compareBookObjects(b, this.theBooks[i]) == 0)
return;
}
if (count<50){
theBooks[count] = b;
count++;
}
else{
System.out.println("No Space to Add More Books.");
}
}
public void searchBySno(){
System.out.println("\t\t\t\tSEARCH BY SERIAL NUMBER\n");
int sNo;
System.out.println("Enter Serial No of Book:");
sNo = input.nextInt();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
return;
}
}
if (flag == 0)
System.out.println("No Book for Serial No " + sNo + " Found.");
}
public void searchByAuthorName(){
System.out.println("\t\t\t\tSEARCH BY AUTHOR'S NAME");
input.nextLine();
System.out.println("Enter Author Name:");
String authorName = input.nextLine();
int flag = 0;
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
if (authorName.equalsIgnoreCase(theBooks[i].authorName)){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
flag++;
}
}
if (flag == 0)
System.out.println("No Books of " + authorName + " Found.");
}
public void showAllBooks(){
System.out.println("\t\t\t\tSHOWING ALL BOOKS\n");
System.out.println("S.No\t\tName\t\tAuthor\t\tAvailable Qty\t\tTotal Qty");
for (int i=0; i<count; i++){
System.out.println(theBooks[i].sNo + "\t\t" + theBooks[i].bookName + "\t\t" + theBooks[i].authorName + "\t\t" +
theBooks[i].bookQtyCopy + "\t\t" + theBooks[i].bookQty);
}
}
public void upgradeBookQty(){
System.out.println("\t\t\t\tUPGRADE QUANTITY OF A BOOK\n");
System.out.println("Enter Serial No of Book");
int sNo = input.nextInt();
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
System.out.println("Enter No of Books to be Added:");
int addingQty = input.nextInt();
theBooks[i].bookQty += addingQty;
theBooks[i].bookQtyCopy += addingQty;
return;
}
}
}
public void dispMenu(){
System.out.println("----------------------------------------------------------------------------------------------------------");
System.out.println("Enter 0 to Exit Application.");
System.out.println("Enter 1 to Add new Book.");
System.out.println("Enter 2 to Upgrade Quantity of a Book.");
System.out.println("Enter 3 to Search a Book.");
System.out.println("Enter 4 to Show All Books.");
System.out.println("Enter 5 to Register Student.");
System.out.println("Enter 6 to Show All Registered Students.");
System.out.println("Enter 7 to Check Out Book. ");
System.out.println("Enter 8 to Check In Book");
System.out.println("-------------------------------------------------------------
---------------------------------------------");
}
public int isAvailable(int sNo){
//returns the index number if available
for (int i=0; i<count; i++){
if (sNo == theBooks[i].sNo){
if(theBooks[i].bookQtyCopy > 0){
System.out.println("Book is Available.");
return i;
}
System.out.println("Book is Unavailable");
return -1;
}
}
System.out.println("No Book of Serial Number " + " Available in Library.");
return -1;
}
public book checkOutBook(){
System.out.println("Enter Serial No of Book to be Checked Out.");
int sNo = input.nextInt();
int bookIndex =isAvailable(sNo);
if (bookIndex!=-1){
//int bookIndex = isAvailable(sNo);
theBooks[bookIndex].bookQtyCopy--;
return theBooks[bookIndex];
}
return null;
}
public void checkInBook(book b){
for (int i=0; i<count; i++){
if (b.equals(theBooks[i]) ){
theBooks[i].bookQtyCopy++;
return;
}
}
}
}
package library;
import java.util.Scanner;
public class student {
String studentName;
String regNum;
book borrowedBooks[] = new book[3];
public int booksCount = 0;
Scanner input = new Scanner(System.in);
public student(){
System.out.println("Enter Student Name:");
this.studentName = input.nextLine();
System.out.println("Enter Reg Number:");
this.regNum = input.nextLine();
}
}
package library;
import java.util.Scanner;
public class students {
Scanner input = new Scanner(System.in);
student theStudents[] = new student[50];
//books book;
public static int count = 0;
public void addStudent(student s){
for (int i=0; i<count; i++){
if(s.regNum.equalsIgnoreCase(theStudents[i].regNum)){
System.out.println("Student of Reg Num " + s.regNum + " is Already Registered.");
return;
}
}
if (count<=50){
theStudents[count] = s;
count++;
}
}
public void showAllStudents(){
System.out.println("Student Name\t\tReg Number");
for (int i=0; i<count; i++){
System.out.println(theStudents[i].studentName + "\t\t" + theStudents[i].regNum);
}
}
public int isStudent(){
//return index number of student if available
//System.out.println("Enter Student Name:");
//String studentName = input.nextLine();
System.out.println("Enter Reg Number:");
String regNum = input.nextLine();
for (int i=0; i<count; i++){
if (theStudents[i].regNum.equalsIgnoreCase(regNum)){
return i;
}
}
System.out.println("Student is not Registered.");
System.out.println("Get Registered First.");
return -1;
}
public void checkOutBook(books book){
int studentIndex =this.isStudent();
if (studentIndex!=-1){
System.out.println("checking out");
book.showAllBooks();//jjjjjjjjjjjj
book b = book.checkOutBook();
System.out.println("checking out");
if (b!= null){
if (theStudents[studentIndex].booksCount<=3){
System.out.println("adding book");
theStudents[studentIndex].borrowedBooks[theStudents[studentIndex].booksCount] = b;
theStudents[studentIndex].booksCount++;
return;
}
else {
System.out.println("Student Can not Borrow more than 3 Books.");
return;
}
}
System.out.println("Book is not Available.");
}
}
public void checkInBook(books book){
int studentIndex = this.isStudent();
if (studentIndex != -1){
System.out.println("S.No\t\t\tBook Name\t\t\tAuthor Name");
student s = theStudents[studentIndex];
for (int i=0; i<s.booksCount; i++){
System.out.println(s.borrowedBooks[i].sNo+ "\t\t\t" + s.borrowedBooks[i].bookName + "\t\t\t"+
s.borrowedBooks[i].authorName);
}
System.out.println("Enter Serial Number of Book to be Checked In:");
int sNo = input.nextInt();
for (int i=0; i<s.booksCount; i++){
if (sNo == s.borrowedBooks[i].sNo){
book.checkInBook(s.borrowedBooks[i]);
s.borrowedBooks[i]=null;
return;
}
}
System.out.println("Book of Serial No "+sNo+"not Found");
}
}
}
package library;
import java.util.Scanner;
public class Library {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("********************Welcome to the Student Library!********************");
System.out.println(" Please Select From The Following Options: ");
System.out.println("**********************************************************************");
books ob = new books();
students obStudent = new students();
int choice;
int searchChoice;
do{
ob.dispMenu();
choice = input.nextInt();
switch(choice){
case 1:
book b = new book();
ob.addBook(b);
break;
case 2:
ob.upgradeBookQty();
break;
case 3:
System.out.println("Enter 1 to Search with Serial No.");
System.out.println("Enter 2 to Search with Author Name(Full Name).");
searchChoice = input.nextInt();
switch(searchChoice){
case 1:
ob.searchBySno();
break;
case 2:
ob.searchByAuthorName();
}
break;
case 4:
ob.showAllBooks();
break;
case 5:
student s = new student();
obStudent.addStudent(s);
break;
case 6:
obStudent.showAllStudents();
break;
case 7:
obStudent.checkOutBook(ob);
break;
case 8:
obStudent.checkInBook(ob);
break;
default:
System.out.println("CHOICE SHOULD BE BETWEEN 0 TO 8.");
}
}
while (choice!=0);
}
}

Comparing user inputted string to an array variable Java

I've included my program below, basically my question is if I input a surname to allow me to find the student I want to delete how can I compare the inputted string to the surname variable in the array?
When I enter the surname and try and compare this to the entries already in the array instead of comparing the surnames it's comparing the inputted string to everything in that instance of it. This is being done in the findStudent method.
I think because i'm passing the entire array here surname contains everything I've entered for that student (surname, forename, exam marks). If I try and just pass the surname parameter i'm getting error messages.
I've searched to see if this was answered already but all I can find is comparing an inputted string to an array that is already defined not an array created from user input.
Any help would be appreciated!
Thanks
import java.util.Scanner;
/**
*
* #author Connor
*/
public class Student {
//declare student variables
private String surname;
private String forename;
private int mark1, mark2, mark3;
private double dblScore;
private static String course = "French";
//constructor
//===========================================================
//
// MODULE : Student
// RETURN TYPE : None
// PARAMETERS : args : String newForename, String newSurname, int newMark1, int newMark2, int newMark3
// DESCRIPTION : Construct Student object
//============================================================
public Student(String newForename, String newSurname, int newMark1, int newMark2, int newMark3) {
this.forename = newForename;
this.surname = newSurname;
this.mark1 = newMark1;
this.mark2 = newMark2;
this.mark3 = newMark3;
this.dblScore = (this.mark1 + this.mark2 + this.mark3) / 3;
}
//===========================================================
//
// MODULE : getCourse
// RETURN TYPE : String course
// PARAMETERS : args :
// DESCRIPTION : get course name
//============================================================
public static String getCourse() {
return course;
}
//===========================================================
//
// MODULE : setCourse
// RETURN TYPE : course
// PARAMETERS : args :
// DESCRIPTION : set course name
//============================================================
public static String setCourse(String newCourse) {
course = newCourse;
return course;
}
//display student details method
//===========================================================
//
// MODULE : displaydetails
// RETURN TYPE : None
// PARAMETERS : args : [DEFAULT]
// DESCRIPTION : write out student details -
// name, course and exam marks
//============================================================
public void displaydetails() {
System.out.println(" ");
System.out.println("Student details - ");
System.out.println("Name - " + surname + " " + forename);
System.out.println("Course - " + course);
System.out.println("exam scores - " + mark1 + " " + mark2 + " " + mark3);
System.out.println("Overall score - " + dblScore);
System.out.println(" ");
}
}
class StudentMenu {
//===========================================================
//
// MODULE : add student
// RETURN TYPE : None
// PARAMETERS : args : studentArray, numStudents
// DESCRIPTION : requests user input to add student to array.
// Upto 6 students can be entered
//============================================================
public static void addStudent(Student[] studentArray, int numStudents) {
String newSurname, newForename;
int newMark1, newMark2, newMark3;
Scanner input = new Scanner(System.in);
System.out.println("1. Add a student");
System.out.println(" ");
System.out.println("Student surname - ");
newSurname = input.next();
input.nextLine();
System.out.println("Student forename - ");
newForename = input.next();
input.nextLine();
System.out.println("First exam mark - ");
newMark1 = input.nextInt();
input.nextLine();
System.out.println("Second exam mark - ");
newMark2 = input.nextInt();
input.nextLine();
System.out.println("Third exam mark - ");
newMark3 = input.nextInt();
input.nextLine();
studentArray[numStudents] = new Student(newSurname, newForename, newMark1, newMark2, newMark3);
}
//===========================================================
//
// MODULE : find student
// RETURN TYPE : int position
// PARAMETERS : args : surname, delSurname, position
// DESCRIPTION : finds the position of the selected student
// in the array
//============================================================
public static void findStudent(Student[] surname,String delSurname, int position, int totalStudents) {
int index;
for (index = 0; index < totalStudents; index++) {
// if (surname[index].equals(delSurname)) {
if (surname[index].equals(delSurname)) {
position = index;
} else {
index++;
}
}
}
//===========================================================
//
// MODULE : delete student
// RETURN TYPE : None
// PARAMETERS : args : myClass, position, NUM_STUDENTS
// DESCRIPTION : deletes chosen student from array. Moves
// all other entries down by one
//============================================================
public static void deleteStudent(Student[] myClass, int position, int NUM_STUDENTS) {
int index = 0;
for (index = position + 1; index < NUM_STUDENTS; index++) {
myClass[index - 1] = myClass[index];
}
}
//===========================================================
//
// MODULE : main method
// RETURN TYPE : None
// PARAMETERS : args : myClass, position, NUM_STUDENTS
// DESCRIPTION : runs menu program allowing user input
// to add/modify/delete student information
//============================================================
public static void main(String[] args) {
//declare scanner
Scanner input = new Scanner(System.in);
//declare variables
boolean menu = true;
int option;
int totalStudents = 0;
final int NUM_STUDENTS = 6;
int position = 0;
String delSurname, newCourse;
//array
Student[] myClass;
myClass = new Student[NUM_STUDENTS];
//main method
//menu
while (menu != false) {
System.out.println("1. Add a student");
System.out.println("2. Delete student");
System.out.println("3. Display all students");
System.out.println("4. Change course details");
System.out.println("5. Search for student");
System.out.println("6. Exit program");
// enter choice
System.out.print("Please enter selection - ");
option = input.nextInt();
System.out.println(" ");
// calling methods using switch
if ((option > 6) || (option < 1)) {
System.out.println("Invalid selection made - reenter. Between options 1-6 only.");
} else {
switch (option) {
case 1:
//option 1 - add student
addStudent(myClass, totalStudents);
totalStudents++;
break;
case 2:
//option 2 - delete student
System.out.println("Student surname to delete - ");
delSurname = input.next();
input.nextLine();
findStudent(myClass,delSurname, position, totalStudents);
if (position >= 0 && position < NUM_STUDENTS) {
deleteStudent(myClass, position, NUM_STUDENTS);
}
totalStudents--;
break;
case 3:
//option 3 - display details
Student.getCourse();
for (int index = 0; index < totalStudents; index++) {
myClass[index].displaydetails();
}
break;
case 4:
//option 4 - change course
Student.getCourse();
System.out.println();
System.out.println("Enter new course details - ");
newCourse = input.next();
input.nextLine();
Student.setCourse(newCourse);
break;
case 5:
//option 5 - search for student by name
System.out.println("Student surname to display - ");
delSurname = input.next();
input.nextLine();
findStudent(myClass,delSurname, position, totalStudents);
if (position >= 0 && position < NUM_STUDENTS) {
myClass[position].displaydetails();
}
break;
case 6:
//option 6 - exit program
menu = false;
break;
}
}
}
}
}
you'll have to check if surname[index].surname.euqals(delSurname) because in your surname array you have Students and not the strings
Right now your code checks if an instance of the class Student is equal to an instance of the class String, which cannot.

Categories

Resources