An application for a temporary management with Java - 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.

Related

Create a program that allows to receive multiples entry data, shows the data from the list

i was told to make a program like that, after input i can see the data
This is my code, please help i had search how to do it but i mostly only if the data is already known not by user input.
is it using an array or using for?
i search many time but i still dont find like mine
ive tried using array but i dont know how to get the array like, there is 3 user input in one array. mostly i found just using one user input
and sometime i get the error where the string cannot meet the int type
import java.util.Scanner;
public class Case7{
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
int choose=0;
String name ="";
String pos = "";
int age = 0;
do{
System.out.println("JOB VACANCY");
System.out.println("===========");
System.out.println("1. Insert new data");
System.out.println("2. List of staff");
System.out.println("3. Search staff");
System.out.println("4. Exit");
System.out.print("Choose: ");
choose = input.nextInt();
if (choose == 1)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
do{
System.out.print("Input staff name: ");
name = input.nextLine();
}while(name.length() < 3 || name.length() > 20);
do{
System.out.print("Input staff position [Manager | Analyst | Programmer]: ");
pos=input.nextLine();
}while(!pos.equalsIgnoreCase("Manager") && !pos.equalsIgnoreCase("Analyst") && !pos.equalsIgnoreCase("Programmer"));
do{
System.out.print("Input staff age: ");
age=input.nextInt();
}while(age <= 17);
System.out.println("Data has been added!");
input.nextLine();
input.nextLine();
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
else if (choose == 2)
{
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
for (int i = 1; i < 6 ; i++ )
{
System.out.println("Staff ID :" + i);
System.out.println("==============");
System.out.println("1. name : " +name );
System.out.println("2. position : " +pos );
System.out.println("3. age : " +age );
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
}
Can I suggest a radically different implementation?
You can use a switch to score the options and You can use a LinkedList to store all the new staff member dinamically.
Here's my commented code:
static LinkedList<Staffer> staff=new LinkedList<>(); //ours database
static Scanner input = new Scanner (System.in);
public static void main(String[] args) {
String s="";
int number=-1;
while(number!=4){ //if your choice is 4, we can exit!
//Chooser:
System.out.print("JOB VACANCY\n===========\n1. Input data\n2. Show Data\n3.Delete Data\n4.£xit\nYour choice: ");
s=input.nextLine();
if(s.matches("\\d+")){ //Check if s is a number
number=Integer.parseInt(s);
switch(number){
case 1: input(); break;
case 2: showData(); break;
case 3: deleteData(); break;
case 4: System.out.println("Goodbye!"); break;
default: System.out.println("Number not valid. Try again!");
}
}else
System.out.println("Number not valid. Try again!");
}
}
private static void showData() {
for(Staffer st:staff)
System.out.println(st);
}
private static void deleteData(/*parameters*/) {
// You can delete a staffer by passing the name, for example
}
private static void input() {
//Plese, implements your data control options...
String name, position;
int age;
System.out.print("Name: ");
name=input.nextLine();
System.out.print("Position: ");
position=input.nextLine();
System.out.print("Age: ");
age=(Integer.parseInt(input.nextLine()));
Staffer staffer=new Staffer(name,position, age);
staff.add(staffer);
}
public static class Staffer{ //a staff member has 3 parameter: name, position and age... You can add others
/*You should store the name using only upperCase or LowerCase, or
* John Williams != john williams != JOHN WILLIAMS and you can have three times
* the same people.
*
* The position can be converted in enum for the same reason.
*/
private String name, position;
private int age;
public Staffer(String name, String position, int age){
this.name=name;
this.position=position;
this.age=age;
}
#Override
public String toString(){
return "Mr. "+name+", "+position+" (age: "+age+")";
}
}
You can see the following example output:
.
Obviously, you have to improve the output and all the data check options.

How do I update a users input in an arraylist?

So I'm making a program for a car dealership as my final project for my class. At this time I'd say I'm about 75% done, but I am having trouble figuring out how to update the users input in an array list. So each array list slot contains the year, make, model, color, and mileage of a car. I can add a new car, I can remove a car, and I can quit my program. I have tried many things, I've read many papers, blogs, forums, and my book for class, but its always updating with the programmers input.
package carDealer;
import java.util.ArrayList;
import java.util.Scanner;
public class VehicleInformation {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
ArrayList<VehicleInventory> car = new ArrayList<VehicleInventory>();
String userInput = "-";
while (!userInput.equals("q")) {
System.out.println("Commands: 'a' to add, 'd' to delete, 'e' to edit, 'q' to quit");
userInput = scnr.next();
if (userInput.equals("a")) {
System.out.println("Year: ");
int year = scnr.nextInt();
System.out.println("Make: ");
String make = scnr.next();
System.out.println("Model: ");
String model = scnr.next();
System.out.println("Color: ");
String color = scnr.next();
System.out.println("Mileage: ");
int mileage = scnr.nextInt();
VehicleInventory userCar = new VehicleInventory();
userCar.setMake(make);
userCar.setModel(model);
userCar.setYear(year);
userCar.setColor(color);
userCar.setMileage(mileage);
userCar.print();
addCar(car, userCar);
}
if (userInput.equals("d")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.remove(userNum - 1);
System.out.println("count: " + car.size());
}
if (userInput.equals("e")) {
for (int i = 0; i < car.size(); ++i) {
System.out.print((i + 1) + " ");
car.get(i).print();
}
System.out.println("List number: ");
int userNum = scnr.nextInt();
car.get(userNum - 1);
You can just do a loop to look up for the car model the user wants to update (it can be any other attribute), and once found update it's value with the desired one:
String vehicleToLookUp = "golf"; // This will be received by user input
String vehicleNewName = "golf gti"; // This will be received by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.get(i).setSomeAttribute(...); // Set the desired attribute here
}
}
Or if you want to substitute the whole object...
String vehicleToLookUp = "golf"; // This will be received by user input
VehicleInventory newVehicle = new VehicleInventory(); // You will set the attributes by user input
for( int i = 0; i < car.size(); i++){
if(vehicleToLookUp.getModel().equals(car.get(i)){
car.set(i, newVehicle ); // Create your object and pass it here
}
}
Also, instead of all those if, you could use if/else if or even a switch/case for better performance/readability (think that even if your logic is true for first if, it will check for all the other if you created, wasting time and processing power.

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

Error when printing out my object from array

Im having some trouble printing out details ive put into my array. when i run my addBook i out in details of two books, but when i select option 2 from menu, i get a runtime error (outofbounds),
Above is resolved by adding [i] to the printline and changing my loop length.
The problem i am having now if my BookID from my loanbook, its not incrementing.
import java.util.Scanner;
public class library {
static Scanner keyboard = new Scanner(System.in);
static boolean run = true;
public static fiction [] fictionArray = new fiction[2];
public static nonfiction [] nonfictionArray = new nonfiction[2];
public static void main (String[] args){ // main class method
while (run){ // this while statement allows the menu to come up again
int answer = 0; // answer initialized to Zero
boolean isNumber;
do{ // start of validation
System.out.println("1. Add book"); // Menu selections
System.out.println("2. Display the books available for loan");
System.out.println("3. Display the books currently on loan");
System.out.println("4. Make a book loan");
System.out.println("5. Return book ");
System.out.println("6 Write book details to file");
if (keyboard.hasNextInt()){ // I would like to set values to =>1 <=6
answer = keyboard.nextInt(); // this is more validation for the input for menu selection
isNumber = true;
} else { // else if number not entered, it will prompt for the correct input
System.out.print(" You must enter a number from the menu to continue. \n");
isNumber = false;
keyboard.next(); // clears keyboard
}
}
while (!(isNumber)); // while to continue program after the do has completed
switch (answer){ // switch statement - uses answer from the keyboard to select a case
case 1:
addBook(); // adds book
break;
case 2:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 6:
break;
}
}
}
static void addBook(){
loanbook [] loanArray = new loanbook[2];
String title,author;
int choice;
for(int x = 0; x < loanArray.length; x++){
System.out.print("Press 1 for Fiction or 2 for Non Fiction: "); // sub menu for fiction and non fiction
choice = keyboard.nextInt();
if (choice == 1){
for(int count = 0; count < fictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
fictionArray[count] = new fiction(title, author);
System.out.println("The book information you entered was : " + fictionArray[count].toString()); // this will show the entry which was inout to the array
count++; }}
else if (choice == 2) {
for(int count = 0; count < nonfictionArray.length; count++){
System.out.print("Enter title: ");
title= keyboard.nextLine();
title= keyboard.nextLine();
System.out.print("Enter author: ");
author= keyboard.nextLine();
nonfictionArray[count] = new nonfiction(title, author);
System.out.println("The book information you entered was : " + nonfictionArray[count].toString()); // this will show the entry which was inout to the array
count++;}}
else{ int noBooks = loanArray.length;
for (int i=0; i<noBooks; i++){
System.out.print(loanArray[x]);
}}}} // addbook
} // Library end
Below is my Superclass , then my subclass
public class loanbook {
private String title,author;
private int bookID;
public loanbook(String pTitle,String pAuthor){
bookID = 0;
title = pTitle;
author = pAuthor;
bookID++;
} // Constructor
public void setTitle(String pTitle){
title = pTitle;
} // setTitle
protected String getTitle(){
return title;
} // getTitle
protected String getAuthor(){
return author;
} // getAuthor
public String toString(){
return "\n BookID: "+ bookID+"\n" + " Title: "+ getTitle()+"\n" +" Author : "+ getAuthor()+ "\n";
}
} // loanbook
My subclasses are the same except for the class name and constructor
public class fiction extends loanbook {
String bookType;
private String getBookType; // Would be fiction
public fiction(String pTitle,String pAuthor){
super(pTitle,pAuthor);
} // constructor
protected void setBookType (String pBookType){
bookType = pBookType;
} // setter for bookType
protected String getBookType(){
return "Fiction";
}
public String toString(){
return super.toString() +" This book is : "+ getBookType();
}
} // class
You've declared your fictionarray and nonfictionarray to be of length 2. However, in your case 2, you are looping 5 times:
for (int i=0; i<5; i++){
if (fictionArray[i] != null){
Change it to 2. It's possible you changed the array length in the declaration, but forgot to change the loop iteration. In that case, you can just use the array's length:
for (int i = 0; i < fictionArray.length; i++) {
Additionally, it looks like you want to print out the specific array element, not the array itself:
System.out.println(fictionArray[i]);
and likewise for nonfictionarray and the nonfiction class.
Two things I see
if (fictionArray[i] != null){
System.out.println(fictionArray);}
if (nonfictionArray[i] != null){
System.out.println(nonfictionArray);}}
You're trying to print the entire array System.out.println(fictionArray). You probably want System.out.println(fictionArray[i])
Also you should set your array sizes to 5 if you want to loop 5 times

Using an array to store input from the user

I'm currently working on this project:
Create a simple Friends class with, as a minimum, the following:
-name and age fields
-appropriate constructors
-get/set methods
-toString() method
Create an ArrayList of Friends.
Write a program to manage your list of friends.
Run the program from a menu with the following options:
-Add a Friend
-Remove a Friend
-Display all Friends
-Exit
and I've come a ways, but I'm not sure I'm heading in the right direction.
Here's what I've got so far:
import java.util.ArrayList;
import java.util.Scanner;
public class Friends
{
public static void main( String[] args )
{
int menu;
menu = 0;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList< Friends > name = new ArrayList< >();
ArrayList< Friends > age = new ArrayList< >();
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while(menu != 4)
{
switch(menu)
{
case 1:
while(choice != 2)
{
System.out.println("Enter Friend's Name: ");
name.add = input.next();
System.out.println("Enter Friend's Age: ");
age.add(input.nextInt());
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
} break;
case 2:
System.out.println("Enter Friend's Name to Remove: ");
name.remove(input.next()); break;
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i));
}
for(int k = 0; k < age.size(); k++)
{
System.out.println(age.get(k));
}break;
}
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
System.out.println("Thank you and goodbye!");
}
public String name;
public int age;
public Friends( String friendsName, int friendsAge )
{
this.name = friendsName;
this.age = friendsAge;
}
public String toString()
{
return super.toString();
}
public void setName( String friendsName )
{
name = friendsName;
}
public void setAge( int friendsAge )
{
age = friendsAge;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
}
I have a few questions:
How do I utilize the Friends class to store user input? (What is wrong with line 34 and 36?)
When I display the friends it shows this:
John
Jen
Jeff
22
24
26
I'd like to have the name and age next to each other rather than all down a line. Any help would be greatly appreciated!
This is where I'm at now, but I messed something up and now it won't allow me to put an argument in "FriendsTest f = new FriendsTest();", but when I don't my friends list just says "null 0"
package friends;
import java.util.ArrayList;
import java.util.Scanner;
public class FriendsTest
{
public static void main( String[] args )
{
int menu;
int choice;
choice = 0;
Scanner input = new Scanner(System.in);
ArrayList< FriendsTest > friends = new ArrayList< >();
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
while(menu != 4)
{
switch(menu)
{
case 1:
while(choice != 2)
{
System.out.println("Enter Friend's Name: ");
String name = input.next();
System.out.println("Enter Friend's Age: ");
int age = input.nextInt();
FriendsTest f = new FriendsTest(name, age);
friends.add(f);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
} break;
case 2:
System.out.println("Enter Friend's Name to Remove: ");
friends.remove(input.next()); break;
case 3:
for(int i = 0; i < friends.size(); i++)
{
System.out.println(friends.get(i).name + " " + friends.get(i).age);
}
break;
}
System.out.println(" 1. Add a Friend ");
System.out.println(" 2. Remove a Friend ");
System.out.println(" 3. Display All Friends ");
System.out.println(" 4. Exit ");
menu = input.nextInt();
}
System.out.println("Thank you and goodbye!");
}
public String name;
public int age;
}
Your logic is off. You never construct a Friends data structure. Also you should have one arrayList of friends and call it friends:
ArrayList<Friends> friends = new ArrayList<>();
This will store you friends data structure. The next thing you need to do is add your friends information to the friends data structure:
while (choice != 2) {
System.out.println("Enter Friend's Name: ");
String name = input.next();
System.out.println("Enter Friend's Age: ");
String age= input.nextInt();
Friends f = new Friends(name, age);
friends.add(f);
System.out.println("Enter another? 1: Yes, 2: No");
choice = input.nextInt();
}
Then to remove a friend, you have a slightly more complicated method where you have to iterate through the arrayList friends until you find the name of the friend then use the .remove() method.
Then to print your friends you would do:
for(int i=0;i<friends.length;i++) {
friends.get(i).toString();
}
Your toString() method in the Friends class should probably look like this:
public void toString()
{
System.out.println(this.getName() + " " + this.getAge());
}
You should use one ArrayList to store all of the information. If the friend class has properties for name and age then you do not need two arraylists to store them. If you follow that approach then
name.Remove(input.next());
will remove both the name and the age.
In order to display both the name and the age in one line, use only one loop to display both like this (assuming you replace names and age with one arraylist called friends):
for(Friend cFriend:friends){
System.out.println(cFriend.getName()+"\t"+cFreind.getAge());
}
There are a few mistakes here. First off, your arraylists aren't properly parametrized and you could do the same with just one list. What you want is:
ArrayList<Friends> listOfFriends = new ArrayList<Friends>();
You then want to modify your case 1 to have add a new instance of friends to the list, so you'd write:
listOfFriends.add(new Friends(name, age));
and remove can be simplified to
listOfFriends.remove(new Friends(name, age));
For your second question, you can fix it by changing the print statement to:
for(int i = 0; i < name.size(); i++)
{
System.out.println(listOfFriends.get(i).name + " " + listOfFriends.get(i).age);
}
break;
That should do it. Good luck!!
Java follow the concept of classes and object. What you have to do is to create a Class named Friend with required fields. Create an arraylist of Friend CLASS in a different java file or Class maybe named as ManageFriends. Also add the 4 cases under this head.
The following doesn't compile because age has been defined of type ArrayList<Friends>
age.add(input.nextInt()); // can't add an `Integer` to a list of `Friends`
For correcting the display modify case 3 to use a single for loop with a single println() within
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i) + " " + age.get(i));
}
break;
assuming the name and age arrays are the same size, you could just do this:
case 3:
for(int i = 0; i < name.size(); i++)
{
System.out.println(name.get(i) + age.get(i));
}
also, there's no reason to store the ages and names in a seperate array, considering you have a Friends class anyway. Just store all the data in an ArrayList<Friends>
ArrayList<Friends> friendList = new ArrayList<Friends>();
string name ="";
int age ="";
System.out.println("Enter Friend's Name: ");
name = input.next();
System.out.println("Enter Friend's Age: ");
age = input.nextInt();
friendList.Add(new Friends(name,age);

Categories

Resources