I need to restructure this class without the use of instance variables - java

So I'm doing a TUI and this was my first iteration.
package bulb.classes;
import java.util.Scanner;
import java.util.ArrayList;
public class RoomTUI {
private ArrayList<Room> rooms;
Scanner scan = new Scanner (System.in);
private int userNumber;
private String userAnswer;
public void run() {
rooms = new ArrayList<Room>();
introduction();
userNumber = 0;
options();
while(userNumber < 5) {
if(userNumber == 1) {
newRoom();
}
if(userNumber == 2) {
addBulbToRoom();
}
if(userNumber == 3) {
clickAllBulbsInRoom();
}
if(userNumber == 4) {
printDescriptionOfBulbs();
}
}
System.out.println("Goodbye");
}
public int getUserInt(String aString) {
System.out.println(aString);
userAnswer = scan.nextLine();
userNumber = Integer.parseInt(userAnswer);
return userNumber;
}
public void displayRooms() {
System.out.println("Possible rooms to choose from.");
String tempString = "";
int roomIndex = 0;
for (int i = 0; i < rooms.size(); i++) {
tempString = tempString + "Room " + roomIndex++ + ": " + rooms.get(i).getDescription() + "\n";
}
System.out.println(tempString);
}
public void introduction() {
System.out.println("Welcome! With this program you can make rooms and design and place the light bulbs for each room you create.");
}
public void options() {
System.out.println("1 : Create a new Room");
System.out.println("2 : Add a bulb to an existing room");
System.out.println("3 : Click all of the bulbs in a particular room");
System.out.println("4 : Display a description of all bulbs in a particular room");
System.out.println("5 : Quit");
getUserInt("What would you like to do?");
}
public void newRoom() {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
rooms.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
public void addBulbToRoom() {
displayRooms();
System.out.println("Which room do you want the bulb in?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println("Please enter the blub's color.");
String color = scan.nextLine();
System.out.println("Please enter the blub's increment amount.");
String incrementS = scan.nextLine();
int incrementI = Integer.parseInt(incrementS);
ThreeWayBulb aBulb = new ThreeWayBulb(color, incrementI);
rooms.get(choiceNumber).addBulb(aBulb);
System.out.println("A " + color + " bulb with and increment of " + incrementI + " was added.");
options();
}
public void clickAllBulbsInRoom() {
displayRooms();
System.out.println("Which room do you want the bulbs clicked?");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
rooms.get(choiceNumber).clickAllBulbs();
System.out.println("The bulbs in " + rooms.get(choiceNumber).getDescription() + " have been clicked.");
options();
}
public void printDescriptionOfBulbs() {
displayRooms();
System.out.println("Please enter a room number.");
String choice = scan.nextLine();
int choiceNumber = Integer.parseInt(choice);
System.out.println(rooms.get(choiceNumber).getDescription() + " with " + rooms.get(choiceNumber).returnSize() + " bulbs: " + "\n" + rooms.get(choiceNumber).toString());
options();
}
}
My instructor wants me to do this without instance variables He said if a method needs the ArrayList that I should make it a parameter and have no instance variables in my TUI. I can't for the life of me figure out how to do that. Also, making it static work fly either. Thanks for any help you can give.

He wants you to declare the ArrayList from a central location (such as the main thread) and then pass it as an argument to the functions that use it. This way if you were to take methods and put them in different classes then it wouldn't break because they're not dependent on this class.
For example if we take your newRoom class:
public void newRoom(List<Room> roomList) {
System.out.println("Please enter a name for your room");
String name = scan.nextLine();
Room aRoom = new Room(name);
roomList.add(aRoom);
System.out.println("You have added the " + name + ".");
options();
}
EDIT: The easiest way to achieve this is to probably move the declaration of rooms to within your run method. Now for each location in the code that reports "unknown variable rooms" you can modify the function to take an ArrayList as a parameter.

Well, eliminating userNumber and userAnswer as members is trivial; their usage is very localized.
For the list, just pass it around after creating it in your main loop.
The scanner is used multiple places; it could also be passed around, I suppose.

Related

How to add objects to arraylist with another class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
Basically my professor told me to make use of arraylist? I don't get his point to be honest.. i think he wants me to add objects to arraylist? which right now, I really have no idea how to do it..
My code is running and is really fine. However, he still wanted me to make use of arraylist to make it look better?
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ahaprogram2;
import java.util.ArrayList;
import java.util.Scanner;
public class AhaProgram {
public static Container container1 = new Container("Container 1: ");
public static Container container2 = new Container("Container 2: ");
public static Container container3 = new Container("Container 3: ");
public static Container container4 = new Container("Container 4: ");
public static Container container5 = new Container("Container 5: ");
public static boolean loop = false;
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Hello! This is the AHA Program of Jalosjos,
Parreno and Alfonso");
System.out.println("Please type the letter of your option");
while (loop != true) {
showOptions();
InputHandler();
}
}
public static void InputHandler() {
Scanner reader = new Scanner(System.in);
String optionletter = reader.nextLine();
if (optionletter.equals("A")) { // OPTION A
System.out.println("There are 5 containers.. What container
will you name? ");
System.out.print("Type the number of your container: ");
String contInput = reader.nextLine();
if (contInput.equals("1")) {
System.out.print("Input the name of Container 1: ");
String ContInp1 = reader.nextLine();
container1.renameCont(ContInp1);
container1.printContainer();
} else if (contInput.equals("2")) {
System.out.print("Input the name of Container 2: ");
String ContInp2 = reader.nextLine();
container2.renameCont(ContInp2);
container2.printContainer();
} else if (contInput.equals("3")) {
System.out.print("Input the name of Container 3: ");
String ContInp3 = reader.nextLine();
container3.renameCont(ContInp3);
container3.printContainer();
} else if (contInput.equals("4")) {
System.out.print("Input the name of Container 4: ");
String ContInp4 = reader.nextLine();
container4.renameCont(ContInp4);
container4.printContainer();
} else if (contInput.equals("5")) {
System.out.print("Input the name of Container 5: ");
String ContInp5 = reader.nextLine();
container5.renameCont(ContInp5);
container5.printContainer();
}
}
if (optionletter.equals("B")) { // for option B
System.out.println("Which container will you use?");
System.out.print("Type a number for the container: ");
String contforAdd = reader.nextLine();
if (contforAdd.equals("1")) {
System.out.print("How many cans will you add?: ");
int numofCans1 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans1; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container1.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("2")) {
System.out.print("How many cans will you add?: ");
int numofCans2 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans2; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container2.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("3")) {
System.out.print("How many cans will you add?: ");
int numofCans3 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans3; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container3.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("4")) {
System.out.print("How many cans will you add?: ");
int numofCans4 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans4; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container4.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
if (contforAdd.equals("5")) {
System.out.print("How many cans will you add?: ");
int numofCans5 = Integer.parseInt(reader.nextLine());
for (int i = 0; i < numofCans5; i++) {
System.out.print("Enter the name of Can " + (i + 1) +
" : ");
String CanName = reader.nextLine();
container5.AddCan(CanName);
}
System.out.println("**CANS ADDED SUCCESSFULLY**");
}
}
if (optionletter.equals("C")) {
System.out.println("Which container will you use?");
System.out.print("Type a number for the container: ");
String contforRemove = reader.nextLine();
if (contforRemove.equals("1")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container1.RemoveCan(canRemove);
}
if (contforRemove.equals("2")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container2.RemoveCan(canRemove);
}
if (contforRemove.equals("3")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container3.RemoveCan(canRemove);
}
if (contforRemove.equals("4")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container4.RemoveCan(canRemove);
}
if (contforRemove.equals("5")) {
System.out.print("What can will you remove?: ");
String canRemove = reader.nextLine();
container5.RemoveCan(canRemove);
}
}
if (optionletter.equals("D")) {
showOptionsDisplay();
System.out.print("Type a letter: ");
String letterDisplay = reader.nextLine();
if (letterDisplay.equals("A")) {
container1.printContents();
System.out.println("");
}
if (letterDisplay.equals("B")) {
container2.printContents();
System.out.println("");
}
if (letterDisplay.equals("C")) {
container3.printContents();
System.out.println("");
}
if (letterDisplay.equals("D")) {
container4.printContents();
System.out.println("");
}
if (letterDisplay.equals("E")) {
container5.printContents();
System.out.println("");
}
if (letterDisplay.equals("F")) {
container1.printContents();
System.out.println("");
container2.printContents();
System.out.println("");
container3.printContents();
System.out.println("");
container4.printContents();
System.out.println("");
container5.printContents();
System.out.println("");
}
}
if (optionletter.equals("E")) {
System.out.println("");
System.out.println("");
System.out.println("");
System.out.println("Thank you for using our program. MWAH!");
loop = true;
}
}
public static void showOptions() {
System.out.println("A = Name Containers");
System.out.println("B = Add Cans");
System.out.println("C = Remove Cans");
System.out.println("D = Display Cans");
System.out.println("E = Quit");
System.out.print("Type a Letter: ");
}
public static void showOptionsDisplay() {
System.out.println("Pick an Option");
System.out.println("A = Display container 1");
System.out.println("B = Display container 2");
System.out.println("C = Display container 3");
System.out.println("D = Display container 4");
System.out.println("E = Display container 5");
System.out.println("F = Display all containers");
}
}
Here is the other class
package ahaprogram2;
import java.util.ArrayList;
import java.util.Scanner;
public class Container {
Scanner reader = new Scanner(System.in);
public ArrayList<String> CanContainer = new ArrayList<String>();
public int Contsizep;
public String contName;
public String changeName;
public Container(String contname){
this.contName = contname;
}
public void AddCan(String CantoAdd) {
this.CanContainer.add(CantoAdd);
}
public void RemoveCan(String CantoRemove) {
if (this.CanContainer.contains(CantoRemove)) {
this.CanContainer.remove(CantoRemove);
System.out.println("** " + CantoRemove + " Can removed
successfully**");
}
else {
System.out.println("Can cannot be found.. make sure to put the
exact name!!");
}
}
public void renameCont(String changename) {
this.contName += changename;
}
public void printContents() {
System.out.println("Here are the contents of " + contName);
System.out.println("");
for(String counter : this.CanContainer){
System.out.println(counter); }
}
public void printContainer() { // for OPTION A ONLY
System.out.println("CONTAINER NAME SUCCESSFUL: ** " + contName +
"**");
}
}
I just would like to put everything to an arraylist
please help.. again my professor doesn't teach us face to face that's why
I'm really trying my best to watch videos in youtube and to ask here also..
A lot of your code seems to predicate on interacting one of five Container objects in similar (if not identical) ways. To start, you can use an ArrayList to store a list of Container objects, instead of manually declaring each container:
public static ArrayList<Container> containerList = new ArrayList<Container>();
You can then populate this list with new containers using ArrayList.add(E e), combined with a for loop or some other construct:
for (int i = 1; i <= 5; i++) {
Container container = new Container("Container " + i + ": ");
containerList.add(container);
}
Likewise, you can access any particular container using ArrayList.get(int index) (if you know the index) or ArrayList.indexOf(Object o) (if you have a reference to a specific container). This can replace or supplement your conditional statements. For instance, your list of (contInput.equals("X")) statements could be replaced with:
int index = Integer.parseInt(contInput);
System.out.print("Input the name of Container " + index + ": ");
Container container = containerList.get(index - 1); // arrays start at 0, but your numbering starts at 1
String contImp = reader.nextLine();
container.renameCont(contImp);
container.printContainer();
Hope this helps.
You can add your containers to ArrayList like this:
ArrayList<Container> containers = new ArrayList<>();
containers.add(new Container("Container 1: "));
containers.add(new Container("Container 2: "));
containers.add(new Container("Container 3: "));
then get them like this:
Container firstContainer = containers.get(0);
Container secondContainer = containers.get(1);

How do I use variables in one method into another method?

So I was wondering if someone could show me how I can call/reference a variable from one method into another method. For example,
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
String p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
String p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
I want to use p1 and p2 from playerNames() inside of coinToss() so I can simply announce who goes first, but I just can't figure out how to call the variables.
My question is not really different compared to others, however I was unable to understand the answers others were given. Once I posted this I got the answer from a bunch of kind people :)
I'm assuming you are new to Java, because it seems you aren't familiar with the concept of fields (i.e. you can put variables outside methods).
public class YourClass {
static String p1;
static String p2;
public static void main(String[] args)
{
System.out.println("Welcome to the game of sticks!");
playerNames();
coinToss();
}
public static void playerNames()
{
Scanner input = new Scanner(System.in);
System.out.println();
System.out.print("Enter player 1's name: ");
p1 = input.nextLine();
System.out.print("Enter player 2's name: ");
p2 = input.nextLine();
System.out.println();
System.out.println("Welcome, " + p1 + " and " + p2 + ".");
}
public static void coinToss()
{
System.out.println("A coin toss will decide who goes first:");
System.out.println();
Random rand = new Random();
int result = rand.nextInt(2);
result = rand.nextInt(2);
if(result == 0)
{
System.out.println(p1 + " goes first!");
}
else
{
System.out.println(p2 + " goes first!");
}
}
}
what you are searching for is called instance variables, check this out.
https://www.tutorialspoint.com/java/java_variable_types.htm
All I had to do was create the instance/static variables outside! Like this:
static String name1;
static String name2;
It was very easy. Thanks everyone for your help!

Trying to print out my ArrayList using one of my methods in my class what am i doing wrong?

Here is my program. All i'm trying to do is print the ArrayList at the end and it won't, what am i doing wrong I'm trying to use mls.ToString() but thats not working. Please tell me what i did wrong. PS this is homework and thanks for the help.
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Book> mls = new ArrayList<Book>();
String userAuthor;
String userTitle;
int userYearPub;
int userPageCount;
String answer;
int numberAnswer;
int choice;
do {
Scanner in = new Scanner(System.in);
System.out.println("Please enter the author of the book.");
userAuthor = in.next();
System.out.println();
System.out.println("Please enter the title of the book.");
userTitle = in.next();
System.out.println();
System.out.println("Please enter the year the book was published.");
userYearPub = in.nextInt();
System.out.println();
System.out.println("Please enter the number of pages of the book.");
userPageCount = in.nextInt();
System.out.println();
Book usersBook = new Book(userAuthor, userTitle, userYearPub, userPageCount);
System.out.println(usersBook.ToString());
System.out.println();
do {
System.out.println("If you want to change anything press one of the following options: ");
System.out.println('1' + " Author.");
System.out.println('2' + " Title.");
System.out.println('3' + " Year it was published.");
System.out.println('4' + " Number of pages");
System.out.println('5' + " Quit");
System.out.println();
choice = in.nextInt();
if (choice == 1) {
System.out.println("Please enter the new author:");
answer = in.next();
usersBook.setAuthor(answer);
}
if (choice == 2) {
System.out.println("Please enter the new title:");
answer = in.next();
usersBook.setTitle(answer);
}
if (choice == 3) {
System.out.println("Please enter the new year:");
numberAnswer = in.nextInt();
usersBook.setYearPub(numberAnswer);
}
if (choice == 4) {
System.out.println("Please enter the new pages count:");
numberAnswer = in.nextInt();
usersBook.setPages(numberAnswer);
}
if (choice == 5) {
break;
}
System.out.println();
System.out.println("Is this correct?");
System.out.println('1' + " yes");
System.out.println('2' + " no");
choice = in.nextInt();
if (choice == 1) break;
}while (choice == 2);
mls.add(usersBook);
System.out.println(usersBook.ToString());
System.out.println();
System.out.println("Do you want to input another book?");
System.out.println("If so press 1, if not press 2.");
choice = in.nextInt();
System.out.println(mls.ToString());
} while (choice == 1);
}
}
Here is the Book class.
public class Book {
private String author;
private String title;
private int yearPub;
private int pages;
public Book(String Author, String Title, int YearPub, int Pages)
{
this.author = Author;
this.title = Title;
this.yearPub = YearPub;
this.pages = Pages;
}
public String ToString()
{
return "The Author of this book is " + author +
"\nThe title of this book is " + title +
"\nThe year published is " + yearPub +
"\nThe number of pages is " + pages;
}
public void setAuthor(String newSring)
{
author = newSring;
}
public void setTitle(String newString)
{
title = newString;
}
public void setYearPub(int newValue)
{
yearPub = newValue;
}
public void setPages(int newValue)
{
pages = newValue;
}
}
mls is not a Book. It is an ArrayList<Book>. You need to fetch the books from the list before calling ToString(). Something like the following:
for(int i = 0; i < mls.size(); i++) {
System.out.println(mls.get(i).ToString());
}
You are triying to access the method ToString of a List of books "mls", which hasn't such method, your variable is not a book is a list of books.
You have to replace "mls.ToString()" for "usersBook.ToString()" in order to access your method.
PS: You should rename your method with lowercase toString, in Java all objects implicitly inherit that method, you can/shall override it.
Problem is line with:
System.out.println(mls.ToString());
ArrayList don't have ToString() method. ArrayList have toString() method.
Solution is:
System.out.println(mls.toString());
or
System.out.println(mls);
You musn't use toString() method, it will be automatically called.
And second problem is that your toString() method in Book class should look like:
#Override
public String toString() {
return "The Author of this book is " + author +
"\nThe title of this book is " + title +
"\nThe year published is " + yearPub +
"\nThe number of pages is " + pages;
}

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);
}
}

Creating a method that searches an Array for a user inputted value, outputs result(s) if any?

I have a program that stores 4 array lists: songName, songArtist, songAlbum & songYear which can be all added to,edited,shuffled and delete by the user. I want to create a method, that when called asks the user to input a string, which then searches the array and prints any corresponding results. For example if I searched the songName array for any song with "The" in the title, they'd output one on each line.
Can anybody help me out with this one? Thanks in advance :)
My Code:
Main Class:
package ca1;
//imports the scanner
import java.util.Scanner;
public class MainClass extends UserInput {
public String nextInt;
public static void main(String[] args) {
//Links to the UserInput class to create an object that stores
//user input
UserInput ui = new UserInput();
//Creates new scanner object
Scanner input = new Scanner(System.in);
//Declares the int "opt" so it can be used in the menu
int opt;
//Calls Methods Class so methods can be used below
Methods methodsFunctions = new Methods();
//initial prompt only displayed when program is first ran
System.out.println("Welcome to your music library");
//Usig a do while loop so that the program keeps running until
//a specific condition is met, in this case it's when 0 is selected.
do
{
//Menu Prompts printed to the screen for the user to select from
System.out.println("........ \n");
System.out.println("Press 0 to Exit\n");
System.out.println("Press 1 to Add a Song\n");
System.out.println("Press 2 to View All Songs\n");
System.out.println("Press 3 to Remove a Song\n");
System.out.println("Press 4 to Edit Song Information\n");
System.out.println("Press 5 to Shuffle Library\n");
System.out.println("Press 6 to Search (by name) \n");
System.out.println("Press 7 to Remove ALL Songs\n");
//Monitors the next Int the user types
opt = input.nextInt();
//"if" statements
if (opt == 0)
{
//This corresponds to the condition of the while loop,
//The program will exit and print "Goodbye!" for the user.
System.out.println("Goodbye!");
}
else if (opt == 1)
{
//This method allows the user to add a song to the library.
//With the format being Title, Artist, Year.
methodsFunctions.addEntry();
}
else if (opt == 2)
{
//This method prints the contents of the Array List to the screen
methodsFunctions.viewAll();
}
else if (opt == 3)
{
//This method allows the user to remove an indiviual song from
//their music library
methodsFunctions.removeOne();
}
else if (opt == 4)
{
//This method allows the user to edit the data of a particular
//and then prints the new value on screen
methodsFunctions.editItem();
}
else if (opt == 5)
{
//This method uses the Collections.shuffle method
//to re-arrange the track list
//song to simulate a music player's shuffle effect.
methodsFunctions.shuffleSongs();
}
else if (opt == 6)
{
methodsFunctions.searchSongs();
}
else if (opt == 7)
{
//This method will clear all contents of the library.
//It will ask the user to confirm their choice.
methodsFunctions.clearAll();
}
else
{
//If the user selects an incorrect number, the console will
//tell the user to try again and the main menu will print again
System.out.println("Incorrect Entry, please try again");
}
} //do-while loop
while (opt > 0);
}
}
Methods Class
package ca1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class Methods extends UserInput
{
Scanner input = new Scanner (System.in);
//Declare array lists
List<String> songName = new ArrayList<>();
List<String> songArtist = new ArrayList<>();
List<String> songAlbum = new ArrayList<>();
List<Integer> songYear = new ArrayList<>();
UserInput ui = new UserInput();
public void clearAll(){
System.out.println("Are you sure?");
System.out.print("1: Yes \n2: No" + "\n");
System.out.print("");
int confirmDelete=input.nextInt();
if (confirmDelete == 1){
songName.clear();
songYear.clear();
System.out.println("Your music library has been cleared");
}
}
public void viewAll(){
System.out.println("\n");
System.out.println("Your Music Library" + "\n" + " Artist - Song - Album (Year) " + "\n");
for (int i = 0; i < songName.size(); i++)
{
int counter=i+1;
System.out.println(counter+": "+songArtist.get(i)+" - "+ songName.get(i)+ " - " + songAlbum.get(i) + " (" +songYear.get(i)+") ");
}
System.out.println("\n");
}
public void addEntry(){
//System.out.print("Enter Name: ");
String newName = ui.getString("Enter the name of the track");
songName.add(newName);
String newArtist = ui.getString("Who performs this track");
songArtist.add(newArtist);
String newAlbum = ui.getString("What album is this track from");
songAlbum.add(newAlbum);
System.out.print("What year was the track released? ");
int newYear=input.nextInt();
songYear.add(newYear);
System.out.println("\n" + "Thank you, " +songName.get(songName.size()-1) + " has been added to the library.");
System.out.println("\n" + "Press 2 to view your library." + "\n");
/*
System.out.println("\n"+songName.get(songName.size()-1));
System.out.println("\n"+songArtist.get(songArtist.size()-1));
System.out.println("\n"+songYear.get(songYear.size()-1));
*/
}
public void removeOne(){
System.out.println(" Which song would you like to delete? (1 to "+songName.size()+")");
viewAll();
int remove=input.nextInt();
if (remove >songName.size()){
System.out.println("Invalid ");
}
else {
remove--;
System.out.println("Are you sure you would like to delete "+songArtist.get(remove)+" - "+songName.get(remove)+ "-" + songAlbum.get(remove) +" (" +songYear.get(remove)+ ") from your music library?");
System.out.print("1: Yes \n2: No" + "\n");
int confirmDelete=input.nextInt();
if (confirmDelete == 1){
songArtist.remove(remove);
songAlbum.remove(remove);
songName.remove(remove);
songYear.remove(remove);
System.out.println(songName.get(remove)+ " has just been removed from your music library");
// viewAll();
}
}
}
public void shuffleSongs(){
//The attributes of the song all get shuffled together because they
//are all linked by the same seed.
long seed = System.nanoTime();
Collections.shuffle(songName, new Random(seed));
Collections.shuffle(songArtist, new Random(seed));
Collections.shuffle(songAlbum, new Random(seed));
Collections.shuffle(songYear, new Random(seed));
System.out.println("Your library is now shuffled" + "\n");
viewAll();
//Shuffles library, then outputs the new library list.
}
public void editItem(){
viewAll();
System.out.println("Choose the song you want to edit (1 to "+songName.size()+")");
//prints out the contents of library with first entry being index 1
//The library is numbered and goes as far as the index of the last entry
int edit=input.nextInt();
if (edit >songName.size()){
System.out.println("Invalid Selection");
//if user selects a number that corresponds to an index that's not
//In the array list, they will be shown an error.
}
else{
edit--;
System.out.println("\n" + "Enter New Track Name: ");
input.nextLine();
String editName=input.nextLine();
songName.set(edit,editName);
//Edits the songName value of the Song object selected
System.out.println("\n" + "Enter New Artist ");
String editArtist=input.nextLine();
songArtist.set(edit,editArtist);
//Edits the songArtist value of the Song object selected
System.out.println("\n" + "Enter New Album ");
String editAlbum=input.nextLine();
songArtist.set(edit,editAlbum);
//Edits the songAlbum value of the Song object selected
System.out.println("\n" + "Enter New Year:");
int editYear;
editYear = input.nextInt();
songYear.set(edit,editYear);
//Edits the songName value of the Song object selected
System.out.print("\n" + "Your changes have been saved:" + "\n");
System.out.print("\n" + "This is your current library");
viewAll();
}
}
public void searchSongs(){
}
}
Everything works, I just want to add the functionality of being able to search.
String to be searched:
String searchString= "the something ok"
Split it into tokens:
String[] tokens = searchString.split("\\s+");
Building a regex pattern to match the said string:
StringBuilder sb = new StringBuilder();
sb.append("(?i)^" + "(?=.*" + tokens[0] + ")");
for (int num = 0; num < tokens.length; num++) {
sb.append("(?=.*" + tokens[num] + ")");
}
Then match each name in your array with that regex patter:
List<String> result = new ArrayList();
for(String i: yourStringArray){
if(i.matches(sb.toString()))
{
result.add(i);
}
}
Then you display the result list:
You can figure out this part your self

Categories

Resources