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

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

Related

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

An application for a temporary management with Java

Hello the StackOverflow community! I am recent Java learner with 1 year of experience only. I was asked to design a software that mimics a school DB, storing all names, class, roll, and other details. When asked to, it would display appropriate messages, like calculating performance, deleting records, etc. It is yet an incomplete work but the first part (accepting and storing details) are done. I have spent a lot of time behind this and the only thing I get is a nullPointerError. Sorry, but I have been asked to stick to the basics, so no glitzy code. I have used inheritance. The superclass is "Student".
public class Student {
int roll,age = 0; // Roll to be auto-updated
String cl,name;
// Marks variables now
int m_eng, m_math, m_physics, m_chem, m_bio = 0;
public Student(){
}
public Student(int a, String cla){
age = a;
cl = cla; // Assign values
}
void setMarks(int eng, int math, int phy, int chem, int bio){
m_eng = eng; m_math = math; m_physics = phy; m_chem = chem; m_bio = bio;
}
}
Here's the error:
java.lang.NullPointerException
at Application.accept_data(Application.java:35)
at Application.execute(Application.java:23)
at Application.input(Application.java:16)
at Application.main(Application.java:101)
Here is the code, though:
import java.util.Scanner;
public class Application extends Student {
static int n; static Scanner sc = new Scanner(System.in);
static Student s[];
void input(){
System.out.println("Enter the number of students: ");
n = sc.nextInt();
s = new Student[n]; // Create array for n students
System.out.println("Enter your choice: ");
System.out.println("1. Accept student's details ");
System.out.println("2. Display all records ");
System.out.println("3. Display data student-wise ");
System.out.println("4. Delete record");
System.out.println("5. Display performance status");
System.out.println("6. Exit");
execute();
}
static void execute(){
boolean correct = false;
while (!correct){
int op = sc.nextInt();
switch(op){
case 1: accept_data(); correct = true;
case 2: disp_data();correct = true;
case 3: disp_studentwise();correct = true;
case 4: del_record();correct = true;
case 5: performance();correct = true;
case 6: System.exit(0); correct = true;//Terminate
default: System.out.println("You must enter a choice. Kindly re-enter: ");correct = false;
}
}
}
static void accept_data(){
for (int i = 0; i<s.length; i++){
s[i].roll = i+1; //Autoupdate roll
System.out.println("Enter name: "); s[i].name = sc.nextLine();
System.out.println("Enter age: "); s[i].age = sc.nextInt(); // Refer to object prope.
System.out.println("Enter class: "); s[i].cl = sc.nextLine();
System.out.println("We're heading for marks entry!");
System.out.println("Enter marks in the following order: ENGLISH, MATH, PHYSICS, CHEMISTRY, BIOLOGY");
s[i].setMarks(sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt(),sc.nextInt());
}
System.out.println("Thanks. Main menu, please enter your choice now: ");
execute();
}
static void disp_data(){
System.out.println("The system will display all stored information of students available.");
for (int i = 0; i<s.length; i++){
if (s[i].roll != -1){
continue; // In case record is deleted, it won't display
}
else {
printrec(i);
}
}
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void disp_studentwise(){
System.out.println("Enter the roll number");
int r = sc.nextInt();
boolean ok = (r>s.length||r<0)?false:true;
while (!ok){
System.out.println("Incorrect roll. Please re-enter: ");
r = sc.nextInt();
if (r>s.length) ok = false;
else ok = true;
}
printrec(r-1);
System.out.println("Main menu, please enter your choice: ");
execute();
}
static void printrec(int n){
int i = n;
System.out.println("For roll number " + s[i].roll + ", details: ");
System.out.println("Name: " + s[i].name); System.out.println("Age: " + s[i].age);
System.out.println("Class: " + s[i].cl);
System.out.println("Subject \t Marks");
System.out.println("English: \t " + s[i].m_eng); // Display record with marks
System.out.println("Maths: \t " + s[i].m_math);
System.out.println("Physics: \t " + s[i].m_physics);
System.out.println("Chemistry: \t " + s[i].m_chem);
System.out.println("Biology: \t " + s[i].m_bio);
}
static void del_record(){
System.out.println("Enter the roll number you want to delete: ");
int rll = sc.nextInt();
for (int i = 0; i<s.length; i++){
if (rll == s[i].roll){
s[i].roll = -1; // Assign non-positive value to refer deleted items
}
}
}
static void performance(){
}
public static void main(String[] args){
Application ob = new Application();
ob.input(); // Start program
}
}
Can anyone point out what's going wrong? Why there's a problem with accepting details of students after pressing for the 1st option? It shows nullPointer on s[i].roll. Keep in mind that roll is autoupdated, and user doesn't intervene there. It serves as a primary key. An explanation would be beneficial, if possible of course, I am eager to learn. Thanks.
this :
s = new Student[n]; // Create array for n students
You are just creating an array of 'n' Student objects here ... that doesn't mean that your 'n' Students are initialized ... your array contains only 'null' values ...
you may want in your accept_data method do a :
for (int i = 0; i<s.length; i++){
s[i] = new Student();
s[i].roll = i+1; //Autoupdate roll
....
You are getting an NPE because you create an array of Students in your input method, but you never populate it with Student objects, so in accept_data, you're trying to access the roll field on a non-existent object.
You will need to fill in the array with new Student objects in your input method before you call accept_data.

Method to display records.

Hey guys just need help on how to finish this up.
Code Snippet:
import java.util.Scanner;
public class CreateLoans implements LoanConstants {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//set the program here
float prime;
float amountOfLoan = 0;
String customerFirstName;
String customerLastName;
String LoanType;
System.out.println("Please Enter the current prime interest rate");
prime = sc.nextInt() / 100f;
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
LoanType = sc.next();
//enter the Loan amount
System.out.println("Enter the amount of loan");
amountOfLoan = sc.nextInt();
//enter Customer Names
System.out.println("Enter First Name");
customerFirstName = sc.next();
System.out.println("Enter Last Name");
customerLastName = sc.next();
//enter the term
System.out.println("Enter the Type of Loan you want. 1 = short tem , 2 = medium term , 3 = long term");
int t = sc.nextInt();
}
}
I need to display the records I have asked and store the object into an array.
so this where I'm stuck. I need to do this in a loop 5 times and by the end display all records in an array, if that makes sense?
Try this way :
import java.util.Scanner;
public class CreateLoans {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Loan[] loans = new Loan[5];
for(int i=0;i<5;i++) {
loans[i] = new Loan();
System.out.println("Please Enter the current prime interest rate");
float prime = sc.nextInt();
prime = (float)(prime/100f);
loans[i].setPrime(prime);
//ask for Personal or Business
System.out.println("are you after a business or personal loan? Type business or personal");
String loanType = sc.next();
loans[i].setLoanType(loanType);
//enter the Loan amount
System.out.println("Enter the amount of loan");
float amountOfLoan = sc.nextFloat();
loans[i].setAmountOfLoan(amountOfLoan);
//enter Customer Names
System.out.println("Enter First Name");
String customerFirstName = sc.next();
loans[i].setCustomerFirstName(customerFirstName);
System.out.println("Enter Last Name");
String customerLastName = sc.next();
loans[i].setCustomerLastName(customerLastName);
}
//Display details
for(int i=0;i<5;i++) {
System.out.println(loans[i]);
}
}
}
class Loan {
private float prime;
private float amountOfLoan = 0;
private String customerFirstName;
private String customerLastName;
private String LoanType;
public float getPrime() {
return prime;
}
public void setPrime(float prime) {
this.prime = prime;
}
public float getAmountOfLoan() {
return amountOfLoan;
}
public void setAmountOfLoan(float amountOfLoan) {
this.amountOfLoan = amountOfLoan;
}
public String getCustomerFirstName() {
return customerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
this.customerFirstName = customerFirstName;
}
public String getCustomerLastName() {
return customerLastName;
}
public void setCustomerLastName(String customerLastName) {
this.customerLastName = customerLastName;
}
public String getLoanType() {
return LoanType;
}
public void setLoanType(String loanType) {
LoanType = loanType;
}
#Override
public String toString() {
return "First Name : " + customerFirstName + "\n" +
"Last Name : " + customerLastName + "\n" +
"Amount of Loan : " + amountOfLoan + "\n" +
"Loan type : " + LoanType + "\n" +
"Prime : " + prime + "\n\n";
}
}
Create a Loan class and put all necessary details as private members into it and override toString() method.
Make a ArrayList and add all the variables inside that list
ArrayList arrlist = new ArrayList();
arrlist.add(prime);
arrlist.add(LoanType);
arrlist.add(amountOfLoan);
arrlist.add(customerFirstName );
arrlist.add(customerLastName);
arrlist.add(t);
and display the ArrayList
System.out.println(arrlist);
Example of a loop
int[] nums = new int[5];
String[] names = new String[5];
Scanner input = new Scanner(System.in);
for (int i = 0; i < 5; i++){
System.out.println("Enter a number: ");
int number = input.nextInt();
// insert into array
nums[i] = number;
System.out.println("Enter a name: ");
String name = input.nextLne();
// insert into array
names[i] = name;
}
Everything you want to be looped 5 times, you can put inside the loop. Whatever values you want to store, you can do that in the loop also.

Running a loop again and passing the control to Main class in Java after output

I am trying to make a simple JAVA program that will help a user select a car of his choice.
public class CarSelector {
static CarSelector start = new CarSelector();
public String BodyType(String a){
String hatchBack, SUV, MUV, compactSedan, sedan, saloon, miniVan, convertible, hybrid, coupe;
if(a.equalsIgnoreCase("a")){
hatchBack = "polo";
System.out.println("We recommend: " +hatchBack);
}
String b = "";
if(a.equalsIgnoreCase("b")){
SUV = "Fortuner";
System.out.println("We recommend: " +SUV);
}
if(a.equalsIgnoreCase("c")){
compactSedan = "Amaze";
System.out.println("We recommend: " +compactSedan);
}
if(a.equalsIgnoreCase("d")){
sedan = "Vento";
System.out.println("We recommend: " +sedan);
}
if(a.equalsIgnoreCase("e")){
saloon = "Corolla";
System.out.println("We recommend: " +saloon);
}
if(a.equalsIgnoreCase("f")){
MUV = "Innova";
System.out.println("We recommend: " +MUV);
}
else{
System.out.println("Incorrect choice.");
System.out.println(a);
//start.BodyType(a);
return null;
}
System.out.println("We recommend: " +a);
return null ;
}
public int PriceRange(){
int price5 = 5;
int price10 = 10;
int price15 = 15;
int price20 = 20;
int price25 = 25;
int price30 = 30;
return 0 ;
}
public String SegmentBest(){
//string type of the best cars within price range
return null;
}
public int OnRoadPrice(){
//return int of on road price
return 0;
}
public String Manufacturer(){
//all manufacturers with their models available
String Toyota, Volkswagen, Honda;
String i1= "Toyota";
String i2= "Volkswagen";
String i3= "Honda";
return null;
}
public int SeatingCapacity(){
//return integer seating capacity
return 0;
}
public String ReviewLink(){
return null;
}
public String LatestReleases(){
return null;
}
public String FuelType(){
return null;
}
public static void main (String[] args){
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
option = input.nextLine();
if( option.equalsIgnoreCase("a")){
System.out.println("A: Hatchback");
System.out.println("B: SUV");
System.out.println("C: MUV");
System.out.println("D: Sedan");
System.out.println("E: Saloon");
System.out.println("F: Compact Sedan");
String optionA = input.nextLine();
start.BodyType(optionA);
}
}
}
The code is simple. A walkthrough: The main class will prompt the user to make a choice of how he wants to choose a car. Given option "A" as a choice will run the first method. Here are my queries
Within the BodyType method, I would like to run the set of IF statements again if the user enters anything other than a,b,c,d,e,f
How can I hand the control back to the main class (run a specific code from MAIN method) and also start a method from another method (from BodyType to PriceRange). I hope I was clear. Thanks, Cheers!
you can play it now...
import java.util.Scanner;
public class CarSelector {
static CarSelector start = new CarSelector();
static String[] bodytypes = new String[]{"hatchBack", "SUV", "MUV", "compactSedan", "sedan",
"saloon", "miniVan", "convertible", "hybrid", "coupe"};
static String[] manufacturers = new String[]{"Toyota", "Volkswagen", "Honda"};
private String getBodyType(int bt) {
if(bt >= bodytypes.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + bodytypes[bt]);
return bodytypes[bt];
}
}
public static String getManufacturer(int mf) {
if(mf >= manufacturers.length){
System.err.println("Incorrect choice.");
return null;
}else{
System.out.println("We recommend: " + manufacturers[mf]);
return manufacturers[mf];
}
}
public static void main(String[] args) {
String bodyType = "";
String manufacturer = "";
Scanner input = new Scanner(System.in);
String option;
System.out.println("Welcome to car selector: ");
System.out.println("Choose according to: ");
pringSelectType();
option = input.nextLine();
while(!option.equalsIgnoreCase("o")){
if (option.equalsIgnoreCase("a")) {
for(int a = 0; a < bodytypes.length ; a++){
System.out.println(a+": "+ bodytypes[a]);
}
option = input.nextLine();
bodyType = start.getBodyType(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else if (option.equalsIgnoreCase("b")) {
for(int a = 0; a < manufacturers.length ; a++){
System.out.println(a+": "+ manufacturers[a]);
}
option = input.nextLine();
manufacturer = getManufacturer(Integer.parseInt(option));
pringSelectType();
option = input.nextLine();
}else{
option = input.nextLine();
System.err.println(("input a right choice"));
pringSelectType();
option = input.nextLine();
}
}
System.out.println("");
System.out.println("it's your choice below: ");
System.out.println("bodyType : "+ bodyType);
System.out.println("manufacturer : "+ manufacturer);
}
private static void pringSelectType() {
System.out.println("A:Body Type");
System.out.println("B: Manufacturer");
System.out.println("C: Price Range");
}
}
i delete some unused method,and change some code.
i don't make any note,cause i think it's easy enough..
if u have some problem,comment it,i will see.
PS:when u want to over the select system,input o.it will be done.

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

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.

Categories

Resources