I am new to OOP and Java Classes, so bear with me.
I am trying to create a class that allows me to store data about books, specifically the fields: Title, Author, Year published, Page count, Genre
Then with that class, I wish to have a main program that runs, asks for a number of books to enter and then allows the user to input the information for each book. Then, a summary is printed for each book.
I have attempted to program a class "bookClass" that allows input of the book information and then a class "bookTest" that creates an array using the bookClass.
This is the bookClass:
public class bookClass {
private String title;
private String author;
private String year;
private String pageCount;
private String genre;
private static int bookCount;
public bookClass(String title, String author, String year, String pageCount, String genre) {
this.setTitle(title);
this.setAuthor(author);
this.setYear(year);
this.setPageCount(pageCount);
this.setGenre(genre);
bookCount++;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setYear(String year) {
this.year = year;
}
public void setPageCount(String pageCount) {
this.pageCount = pageCount;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getYear() {
return year;
}
public String getPageCount() {
return pageCount;
}
public String getGenre() {
return genre;
}
public int getBookCount() {
return bookCount
}
}
This is the main class:
import java.util.*;
public class bookTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
System.out.print("How many books would you like to enter: ");
int bookAmount = input.nextInt(); input.nextLine();
String[][] books2DArray = new String[bookAmount][5];
for (String[] books1DArray: books2DArray) {
System.out.print("Please enter the title: ");
String title = input.nextLine();
System.out.print("Please enter the author ");
String author = input.nextLine();
System.out.print("Please enter the year: ");
String year = input.nextLine();
System.out.print("Please enter the page count: ");
String pageCount = input.nextLine();
System.out.print("Please enter the genre: ");
String genre = input.nextLine();
bookClass book = new bookClass(title, author, year, pageCount, genre);
books1DArray[0] = book.getTitle();
books1DArray[1] = book.getAuthor();
books1DArray[2] = book.getYear();
books1DArray[3] = book.getPageCount();
books1DArray[4] = book.getGenre();
}
for (String[] books1DArray: books2DArray) {
printSummary( books1DArray[0], books1DArray[1], books1DArray[2], books1DArray[3], books1DArray[4]);
}
System.out.println("There are" + book.getBookCount() + "books in the system");
}
public static void printSummary(String title, String author, String year, String pageCount, String genre) {
System.out.format("%s written by %s was published in %s, has %s pages and is of the %s genre", title, author, year, pageCount, genre);
}
}
I have multiple issues/questions:
Would it be better to create the array in the main class?
I feel like I am being highly inefficient as it feels like I am repeating myself in the code over and over. Some of the redundancy is necessary for good practice (such as getters and setters), but am I overdoing it?
In the for loop in the main class, I want to create multiple objects and add them to the array, but I am unsure how to do that as it would require different names to avoid being overwritten.
Also, calling getBookCount at the end of my main class does not work. Is there a reason for this?
I would appreciate any general advice or other things you may notice, as I feel as though I am fundamentally misunderstanding the use of Java classes.
You are learning Java, so you should learn Java name conventions.
I assume your book class public class BookClass, you can write your test class that uses 1 array of BookClass (or ArrayList or any collection type you want), for example (Skip input checking)
public class BookTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("How many books would you like to enter: ");
int bookAmount = input.nextInt(); input.nextLine();
BookClass[] books = new BookClass[bookAmount];
for (int i = 0; i < bookAmount; i++) {
System.out.print("Please enter the title: ");
String title = input.nextLine();
System.out.print("Please enter the author ");
String author = input.nextLine();
System.out.print("Please enter the year: ");
String year = input.nextLine();
System.out.print("Please enter the page count: ");
String pageCount = input.nextLine();
System.out.print("Please enter the genre: ");
String genre = input.nextLine();
books[i] = new BookClass(title, author, year, pageCount, genre);
}
for (BookClass book : books) {
printSummary(book.getTitle(), book.getAuthor(), book.getYear(), book.getPageCount(), book.getGenre());
}
System.out.println("There are" + books.length + "books in the system");
}
public static void printSummary(String title, String author, String year, String pageCount, String genre) {
System.out.format("%s written by %s was published in %s, has %s pages and is of the %s genre", title, author, year, pageCount, genre);
}
}
You don't need static attribute in BookClass to store the number of books, you have many ways to do it.
Your getBookCount does not work because you call an undefined parameter book which you defined in side for loop. If you want, you should define a static getter method public static int getBookCount(), and access it BookClass.getBookCount(). But I advice you to do not use it to count object, because it can make wrong in complicated program when you remove object, use multi-threading with out synchronization ...
Related
Basically, I just tried to learn linked lists but I can't seem to understand how to insert a bunch of data from different variables into it. Does it work as an array/ ArrayList? Before we end the loop we are supposed to store the data right, but how??
Let say I have variables ( name, age, phonenum).
'''
char stop='Y';
while(stop!='N'){
System.out.println("\nEnter your name : ");
int name= input.nextLine();
System.out.println("\nEnter your age: ");
int age= input.nextInt();
System.out.println("\nEnter your phone number: ");
int phonenum= input.nextLine();
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
stop = sc.nextLine().charAt(0);
}
'''
First, change your code to use appropriate types. Name and phone should be of type String, not int.
Define a class to hold your fields. Records are an easy way to do that.
record Person ( String name , int age , String phone ) {}
Declare your list to hold objects of that class.
List< Person > list = new LinkedList<>() ;
Instantiate some Person objects, and add to list.
list.add( New Person( "Alice" , 29 , "477.555.1234" ) ) ;
In the line above, I hard-coded some example data. In your own code, you will be passing to the constructor the variables you populated by interacting with the user.
list.add( New Person( name , age , phonenum ) ) ;
You can create an object which has name, age and phenomenon then create an insert method which you call in your while loop.
In psuedo code it would look something like this:
public class Data {
String name;
int age;
int phenomenon;
//constructor
//getters & setters
}
This class above will hold contain the user input. You can gather all the user input and store it in an array and perform the insert with array of data instead of inserting one object at a time
public void InsertData(LinkedList<Data> list, Arraylist<Data> input) {
for(Data d: input){
list.add(d);
}
}
You can read up on linkedlists a bit more here to understand how exactly linkedlists work and implement your own from scratch: https://www.geeksforgeeks.org/implementing-a-linked-list-in-java-using-class/
Try this
Possibility : 1
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<Object> list = new LinkedList<Object>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(name);
list.add(age);
list.add(phonenum);
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
possibility : 2
import java.util.*;
public class Naddy {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char stop = 'Y';
LinkedList<User> list = new LinkedList<User>();
while (stop != 'N') {
System.out.println("\nEnter your name : ");
String name = input.nextLine();
System.out.println("\nEnter your age: ");
int age = input.nextInt();
System.out.println("\nEnter your phone number: ");
long phonenum = input.nextLong();
list.add(new User(name, age, phonenum));
System.out.println("Enter 'Y' to continue, 'N' to Stop: ");
input.nextLine();
stop = input.nextLine().charAt(0);
}
System.out.println(list);
}
}
class User {
private String name;
private int age;
private long phonenum;
public User() {
}
public User(String name, int age, long phonenum) {
this.name = name;
this.age = age;
this.phonenum = phonenum;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public long getPhonenum() {
return phonenum;
}
public void setPhonenum(long phonenum) {
this.phonenum = phonenum;
}
#Override
public String toString() {
return "User [age=" + age + ", name=" + name + ", phonenum=" + phonenum + "]";
}
}
I made a list for my teachers and print out the list. The list prints, but the problem is that my list prints out null for all values in my list. It gives me null for first name, last name, id and course. What am I doing wrong??? How can I fix this? I want to be able to print out my actual values in my list of teachers. I don't see what could be the issue if I'm being totally honest. I add the first name, last name, id and course to the teacher list correctly. So, what am I missing?
Error:
Main.java code:
package SchoolSystem;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class main{
public static void main(String[] args) throws InterruptedException {
int ch; //user choice
teacher teachers = new teacher();
student students = new student();
//add teachers
List<teacher> teach = new ArrayList<>();
teach.add(new teacher(teachers.first_name, teachers.last_name, teachers.teacher_id, teachers.course));
Scanner sc = new Scanner(System.in);
loop : while (true) {
//menu
System.out.println("");
System.out.println("1: Add Teacher"); //user can add a teachers name, id, and course
System.out.println("2: Add Student"); //user can add a students name, id, courses, and GPA
System.out.println("3: All Teachers"); //user can access teacher list and change items
System.out.println("4: All students"); //user can access student list and change items
System.out.println("5: Exit Program");
System.out.print("Enter your choice: ");
ch = sc.nextInt();
System.out.println("");
switch (ch) {
case 1:
System.out.println("Enter teacher's first name: ");
teachers.first_name = sc.next();
System.out.println("Enter teacher's last name: ");
teachers.last_name = sc.next();
System.out.println("Enter teacher's id: ");
teachers.teacher_id = sc.next();
System.out.println("Enter teacher's course: ");
teachers.course = sc.next();
break;
case 2:
System.out.println("Enter student's first name: ");
students.first_name = sc.next();
System.out.println("Enter student's last name: ");
students.last_name = sc.next();
System.out.println("Enter student's id: ");
students.student_id = sc.next();
System.out.println("Enter student's course: ");
students.course = sc.next();
break;
case 3:
System.out.println("-----------------------------------------------------------------------------");
System.out.printf("%1s %20s %5s %5s", "FIRSTNAME", "LASTNAME", "ID", "COURSE");
System.out.println();
System.out.println("-----------------------------------------------------------------------------");
for(teacher teacher: teach){
System.out.format("%1s %20s %5s %5s",
teacher.getFirstName(), teacher.getLastName(), teacher.getId(), teacher.getCourse());
System.out.println();
}
System.out.println("-----------------------------------------------------------------------------");
break;
case 4:
//null
break;
case 5:
/*
System.out.println("Exiting Program....");
TimeUnit.SECONDS.sleep(3);
System.out.println("Goodbye!");
break loop;
*/
break;
default:
//System.out.println("Invalid choice! Please enter an option (1 - 5)");
}
}
}
}
Teacher.java code:
package SchoolSystem;
public class teacher {
public teacher() {
//null
}
public String first_name;
public String last_name;
public String teacher_id;
public String course;
public teacher(String first_name, String last_name, String teacher_id, String course) {
this.first_name = first_name;
this.last_name = last_name;
this.teacher_id = teacher_id;
this.course = course;
}
//return firstname
public String getFirstName() {
return first_name;
}
//return lastname
public String getLastName() {
return last_name;
}
//return teacherId
public String getId() {
return teacher_id;
}
//return course
public String getCourse() {
return course;
}
}
in Teacher Class you must add setters
public class Teacher {
public Teacher() {
//null
}
public String first_name;
public String last_name;
public String teacher_id;
public String course;
public Teacher(String first_name, String last_name, String teacher_id, String course) {
this.first_name = first_name;
this.last_name = last_name;
this.teacher_id = teacher_id;
this.course = course;
}
//return firstname
public String getFirstName() {
return first_name;
}
public void setFirstName(String firstName) {
this.first_name = firstName;
}
//return lastname
public String getLastName() {
return last_name;
}
public void setLastName(String lastName) {
this.last_name = lastName;
}
//return teacherId
public String getId() {
return teacher_id;
}
public void setId(String id) {
this.teacher_id = id;
}
//return course
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
in Main
delete this line
teach.add(new Teacher(teachers.getFirstName(), teacher.getLastName(), teacher.getId(), teacher.getCourse()));
and write:
int ch; //user choice
//add teachers
List<Teacher> teach = new ArrayList<>();
Scanner sc = new Scanner(System.in);
// teach.add(new Teacher(teachers.getFirstName(), teacher.getLastName(), teacher.getId(), teacher.getCourse()));
loop : while (true) {
//menu
System.out.println("");
System.out.println("1: Add Teacher"); //user can add a teachers name, id, and course
System.out.println("2: Add Student"); //user can add a students name, id, courses, and GPA
System.out.println("3: All Teachers"); //user can access teacher list and change items
System.out.println("4: All students"); //user can access student list and change items
System.out.println("5: Exit Program");
System.out.print("Enter your choice: ");
ch = sc.nextInt();
System.out.println("");
switch (ch) {
case 1:
Teacher teachers = new Teacher();
System.out.println("Enter teacher's first name: ");
teachers.setFirstName(sc.next());
System.out.println("Enter teacher's last name: ");
teachers.setLastName(sc.next());
System.out.println("Enter teacher's id: ");
teachers.setId(sc.next() );
System.out.println("Enter teacher's course: ");
teachers.setCourse (sc.next());
teach.add(teachers);
break;
case 2:
// .....
use setters to add values and add "teachers" oject to List
teach.add(teachers);
You are having OOP issues with your code.
teacher teachers = new teacher();
...
List<teacher> teach = new ArrayList<>();
teach.add(new teacher(teachers.first_name, teachers.last_name, teachers.teacher_id, teachers.course));
This snippet takes a new instance of a teacher and then creates a brand new instance of teacher to add to the list. These are 2 distinct objects. I'm assuming you are coming from C or C++ and you are thinking of them as pointers? Fortunately, that's not how Java works.
You can simply add the "teachers" variable to the "teach" list. Then when you later update the "teachers" object, the data will be available in the "teach" list.
The caveat to this is you need to instantiate a new object for "teachers" inside the loop, as well as moving the modified teach.add(teachers); into the loop.
List<teacher> teach = new ArrayList<>();
List<student> stud = new ArrayList<>();
Scanner sc = new Scanner(System.in);
loop : while (true) {
...
switch (ch) {
case 1:
teacher teachers = new teacher();
...
teach.add(teachers);
break;
case 2:
student students = new student();
...
stud.Add(students);
break;
...
Now you have a new teacher object for every teacher as well as a list containing only valid data, rather than empty objects.
This works because "teach" now contains a reference to the instance of "teachers". This is similar to the pointers of C and C++ I mentioned earlier. In this case, you have a reference to the whole object, not to the individual properties of the object you were trying to have earlier.
Think of an object as a piece of paper and a list as a box. You can put all kinds of data on the paper, then put the piece of paper in the box. When you need a new object, you get a new piece of paper, write the data on it, and add it to the box. Then when you want to update an object, you find it in the box and update the data. It's that simple. You can have a complex object where it has instances of other objects in it, but that's beyond the scope of your question.
On a side note
Classes teacher and student should be capitalized as Teacher and Student. The list of Teachers should be named "teachers" and a single Teacher object should be named "teacher", or something that won't be confused with the class name. In general, lists should be plural and a singular instance should be singular.
So this is a rough work in progress. I am making a text based information kiosk where people can do a search by author, title, etc. Right now I am having a hard time adding book using the kiosk. I can add all the info, but after I enter the information per book, I get a No Such Element exception. No sure what that means and any help would be appreciated.
import java.util.Scanner;
import java.util.ArrayList;
public class Books{
public static void main(String[] args) {
//Part 1: Initialize the MIS
//Part 1.1: Open Scanner
Scanner keyboard = new Scanner(System.in);
//Part 1.2: Build a store
Store newstore = new Store();
//Part 1.3: Build an array of books
final int MAX_NUM_BOOKS = 500;
Books[] list_book = new Books[MAX_NUM_BOOKS];
//Part 1.4: Prompt for the initial book count
System.out.println("How many books do we have?");
int bookcount = keyboard.nextInt();
//Part 1.5: Builds the books
for(int i=0; i<bookcount; i++) list_book[i] = new Books();
//Part 1.6: Create switch menu
boolean exit = false;
while(!exit){
System.out.println("Please make a selection: ");
System.out.println("To search by Title (0)");
System.out.println("To search by Author's Last name (1)");
System.out.println("To search by Author's First name (2)");
System.out.println("To search by ISBN (3)");
System.out.println("To add a book to the inventory (4)");
System.out.println("To exit (5)");
int option = keyboard.nextInt();
switch(option){
case 0:System.out.print("Please enter the title of the book you are looking for: ");
String title = keyboard.next();
results(Book.TitleSearch(title));
break;
case 1: System.out.print("Please enter the last name of the author you are looking for: ");
String auth_last = keyboard.next();
results(Book.Auth_LastSearch(auth_last));
break;
case 2:System.out.print("Please enter the first name of the author you are looking for: ");
String auth_first = keyboard.next();
results(Book.Auth_FirstSearch(auth_first));
break;
case 3:System.out.print("Please enter the ISBN of the book you are looking for: ");
String ISBN = keyboard.next();
results(Book.ISBNSearch(ISBN));
break;
case 4:addBook(newstore);
break;
case 5: exit=true;
}//switch
}//while
//Part :Close Input
keyboard.close();
}
//Part 2: Add Books to the Store
private static void addBook(Store newstore) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter title of the book: ");
String title = keyboard.next();
System.out.print("Enter Author's first name: ");
String auth_first_nam = keyboard.next();
System.out.print("Enter Author's last name: ");
String auth_last_nam = keyboard.next();
System.out.print("Enter the ISBN: ");
String isbn = keyboard.next();
Book book = new Book(title, auth_first_nam, auth_last_nam, isbn);
Store.addBook(book);
keyboard.close();
}
private static String results(String titleSearch) {
return Book.output();
}
}
//Build each individual book
class Book{
private static String title;
private static String auth_first_nam;
private static String auth_last_nam;
private static String isbn;
private static String bookinfo;
public Book(Scanner keyboard){
System.out.println("Enter the book Title: ");
title=keyboard.next();
System.out.println("Enter in the Author's Last Name: ");
auth_last_nam=keyboard.next();
System.out.println("Enter in the Author's First Name: ");
auth_first_nam=keyboard.next();
System.out.println("Enter the ISBN number: ");
isbn=keyboard.next();
}
public Book(String title, String auth_first_nam, String auth_last_nam, String isbn) {
}
public static String output() {
bookinfo=(title+" by " + auth_first_nam + " " + auth_last_nam + ". ISBN: " +isbn);
return bookinfo;
}
public static String ISBNSearch(String iSBN2) {
return isbn;
}
public static String Auth_FirstSearch(String auth_first) {
return auth_first_nam;
}
public static String Auth_LastSearch(String auth_last) {
return auth_last_nam;
}
public static String TitleSearch(String title2) {
return title;
}
public String getTitle() {
return title;
}
public String GetAuthorLast(){
return auth_last_nam;
}
public String GetAuthorFirst(){
return auth_last_nam;
}
public String getISBN() {
return isbn;
}
}
class Store{
private static ArrayList<Book> books;
private static Book book;
public Store(){
books = new ArrayList<Book>();
}
public static void addBook(Book Book){
if(book==null){
System.out.println("I'm sorry, but you didn't enter in any information.");
return;
}
else{
books.add(Book);
}
}
public Book getTitle(String title){
for(int i=0;i<books.size(); i++)
{
if(books.get(i).getTitle().equals(title))
{
book=books.get(i);
}
}
return book;
}
public ArrayList<Book> findAutLast(String aut_last_nam)
{
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size(); i++)
{
Book current = books.get(i);
if(current.GetAuthorLast().indexOf(aut_last_nam) >=0)
{
found.add(current);
}
}
return found;
}
public ArrayList<Book> findTitle(String title){
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size();i++)
{
Book current = books.get(i);
if (current.getTitle().indexOf(title) >=0)
{
found.add(current);
}
}
return found;
}
public ArrayList<Book> findISBN(String isbn)
{
ArrayList<Book> found = new ArrayList<Book>();
for(int i=0; i<books.size(); i++)
{
Book current = books.get(i);
if(current.getISBN().indexOf(isbn) >=0)
{
found.add(current);
}
}
return found;
}
}
Sorry, there's some dead code and loose ends still being tied up. Just really curious about the No Element as I've never seen it before. It happens at line 35 after using the Switch for case 4.
The issue is actually in this method:
private static void addBook(Store newstore) {
...
keyboard.close();
}
Where you close the keyboard instance of a Scanner.
The loop in which you call addBook is making use of the keyboard scanner, and the next time through the loop calls keyboard.nextInt() fails, because the scanner is closed.
I deduced this by running your code, and observing the following exception:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:838)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Books.main(Books.java:36)
Notably, line 36 is
int option = keyboard.nextInt();
And I only hit this exception after running option 4 (add a book).
If you remove keyboard.close() from your addBook() method, your program will no longer crash.
I don't expect your program to work, as you have a number of other errors (misuse of static fields and methods), but it will no longer throw a NoSuchElementException.
As a hint (since this appears to be homework), the other problems I'm seeing in your program:
static fields for Book (so the properties you wish to define on a book won't persist with the object)
static method son Book (similar to above)
failure to set fields in Book using the appropriate constructor (and repeating code from addBook in an inappropriate constructor)
Creating a Books[] instead of what you likely want, which is a Book[] (or maybe this is irrelvant since you have an ArrayList<Book> books in Store
Though it's really hard to tell because you haven't provided the stacktrace, I could see a problem arrising when to access an element in the ArrayList. It's hard to tell just by staring at your code, but I would start by fixing this
private static String title;
private static String auth_first_nam;
private static String auth_last_nam;
private static String isbn;
private static String bookinfo;
All of these fields you have as static. That means that for every Book you create and add the ArrayList of books, every single one will have the exact same title, auth_first_nan, auth_last_nam, isbn, and bookinfo. That could cause a problem in the program. Though probably doesn't cause the NoSuchElementException, I would still make this fix.
For example, if you first add a Book with title "StackOverflow", then you add a Book with title "StackExchange", the first Book's title also become "StackExchange". That means that if you ever try and access a Book by title "StackOverflow", you would never find it
Change all the fields to not include the static
private String title;
private String auth_first_nam;
private String auth_last_nam;
private String isbn;
private String bookinfo;
Check out Java tutorial for static keyword
My code is not compiling and my biggest issue is that line 32 compiles but 42 does not and the methods they come from are written exactly the same. The error message is error cannot find symbol.
import java.util.*;
import java.text.*;
public class CourseApp{
public static void main(String[] args){
Scanner s = new Scanner (System.in);
DecimalFormat df = new DecimalFormat("$0.00");
int initialSize;
boolean q = true;
System.out.println("Enter how many courses you would like to enter info rmation for? ");
try{initialSize = s.nextInt();}
catch(NumberFormatException sonic){
while(initialSize <= 0){
System.out.println("Please enter an integer greater than 0 (ie5). ");
initialSize = s.nextInt();}}
ArrayList <Course> courseArrayList = new ArrayList<Course> (initialSize);
String number="";
String name="";
String instr="";
String text="";
for (int i = 0; i < initialSize; i++){
courseArrayList.add(new Course(number, name, instr, text));
System.out.println("Enter in course information. ");
do{
courseArrayList.get(i).setNumber("");
System.out.println("Please enter the course number: ");
courseArrayList.get(i).setNumber(s.nextLine());
}while(courseArrayList.get(i).getNumber().equals(""));
do{
courseArrayList.get(i).setName("");
System.out.println("Please enter the course name: ");
courseArrayList.get(i).setName(s.nextLine());
}while(courseArrayList.get(i).getName().equals(""));
do{
courseArrayList.get(i).setLastName("");
System.out.println("Please enter the Instructor's last name: ");
courseArrayList.get(i).setLastName(s.nextLine());
}while(courseArrayList.get(i).getLastName().equals(""));
do{
courseArrayList.get(i).setFirstName("");
System.out.println("Please enter the Instructor's first name: ");
courseArrayList.get(i).setFirstName(s.nextLine());
}while(courseArrayList.get(i).getFirstName().equals(""));
do{
courseArrayList.get(i).setUserName("");
System.out.println("Please enter the Instructor's user name: ");
courseArrayList.get(i).setUserName(s.nextLine());
}while(courseArrayList.get(i).getUserName().equals(""));
String[] instrr = new String[3];
instrr[0]=courseArrayList.get(i).getLastName()+", ";
instrr[1]=courseArrayList.get(i).getFirstName()+"\n";
instrr[2]=courseArrayList.get(i).getUserName()+"#K-State.ksu";
instr = instrr[0]+instrr[1]+instrr[2];
System.out.println("Please enter the required text book's title: ");
courseArrayList.get(i).setTitle(s.nextLine());
System.out.println("Please enter the required text book's author: ");
courseArrayList.get(i).setAuthor(s.nextLine());
System.out.println("Please enter the required text book's price: ");
try{courseArrayList.get(i).setPrice(s.nextDouble());}
catch(NumberFormatException shadow){
while(courseArrayList.get(i).setPrice(s.nextDouble()) < 0){
System.out.println("Please enter a positive numerical value. ");
courseArrayList.get(i).setPrice(s.nextDouble());}}
String[] textt = new String[3];
textt[0]=courseArrayList.get(i).getTitle()+"\n";
textt[1]=courseArrayList.get(i).getAuthor()+"\n";
textt[2]=df.format(courseArrayList.get(i).getPrice())+"\n";
text = textt[0]+textt[1]+textt[2];}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}
System.out.println("Please enter a course number");
String a = s.nextLine();
for (int i = 0; i < initialSize; i++){
if (a.equals(courseArrayList.get(i).getNumber())){
courseArrayList.remove(i);}
else if (! a.equals(courseArrayList.get(initialSize-1).getNumber())){
do {
System.out.println("Course number not found.");
System.out.println("Please enter a valid course number: ");
a = s.nextLine();
for (int j = 0; j < initialSize; j++){
if (a.equals(courseArrayList.get(j).getNumber())){
q=false;
courseArrayList.remove(j);}}
} while (q=true);}
else {}}
for (int i = 0; i < initialSize; i++){
System.out.println("Press enter to display each of the courses");
s.nextLine();
courseArrayList.get(i).toString();}}}
this is from a different class and this part does not compile
public void setLastName(String lname){
lastName=lname;}
the instructor class is:
public class Instructor
{
private String lastName; // Last name
private String firstName; // First name
private String userName; // Username ID
public Instructor(String lname, String fname, String un){
lastName = lname;
firstName = fname;
userName = un;}
public Instructor(Instructor object2){
lastName = object2.lastName;
firstName = object2.firstName;
userName = object2.userName;}
public void setLastName(String lname){
lastName=lname;}
public String getLastName(){
return lastName;}
public void setFirstName(String fname){
firstName=fname;}
public String getFirstName(){
return firstName;}
public void setUserName(String un){
userName=un;}
public String getUserName(){
return userName;}
public String toString()
{
return str;
}
}
this is from a different class and this part does compile
public void setName(String name){
courseName=name;}
the course class is:
public class Course
{
private String courseNumber; // e.g. CIS 200
private String courseName; // e.g. Programming Fundamentals
private Instructor instructor; // Course instructor (object)
private TextBook textBook; // Required Course textbook (object)
public Course(String number, String name, String instr, String text){
courseNumber = number;
courseName = name;
instructor = new Instructor(instr);
textBook = new TextBook(text);}
public String getName(){
return courseName;}
public void setName(String name){
courseName=name;}
public String getNumber(){
return courseNumber;}
public void setNumber(String number){
courseNumber=number;}
public Instructor getInstructor(){return new Instructor(instructor);}
/**getTextBook method
#return A reference to a copy of this course's TextBook object.*/
public TextBook getTextBook(){return new TextBook(textBook);}
/**toString method
#return A string containing the course information.*/
public String toString(){
String str = courseNumber + " " + courseName+ "\n"+
instr+"\n" +
text;
return str;}}
And finally the TextBook class:
import java.text.*;
import java.util.*;
public class TextBook
{
DecimalFormat df = new DecimalFormat("$0.00");
private String title; // Title of the book
private String author; // Author's last name
private double price; // Wholesale cost of the book
public TextBook(String t, String a, double p){
title = t;
author = a;
price = p;}
public TextBook(TextBook object2){
title = object2.title;
author = object2.author;
price = object2.price;}
public void setTitle(String t){
title=t;}
public void setAuthor(String a){
author=a;}
public void setPrice(String p){
price=p;}
public void getTitle(){
return title;}
public void getAuthor(){
return author;}
public void getPrice(){
return price;}
public String toString(){
String str = "Required Textbook: \n" + " " + title+", " + author + ", " + df.format(price);
return str;}}
why does .setLastName() not work but .setName() does
In your class that has this
public void setLastName(String lname){
lastName=lname;
}
Make sure lastName exists as class variable. I am guessing this should be like:
private String lastName;
If you post your Course.java code, we all would be better equipped to explain what might be missing.
I am making a program for a library; the library contains different items such as book, videos, journals, ect...
I have a class called item with basic methods for every item in the library, and my classes for book, video, journal and all other items extend Item. I want to make an array to contain all of the items in the library so people can search for a specific item, it will find it in the array and display the info for that item.
The problem I'm having is that when I create an array of type Item I can only call methods of the Item class and I can't call the new methods I made for book in the book class or for journal in the journal class.
So I'm forced to have separate arrays for each of the different types of Items.
Is there a way to have just one array that can call methods from all the different classes for each item?
You can see my code below; I have only attached the code for my tester class where the array is, let me know if you need to see the code for the other classes. I would appreciate any help.
import java.util.Arrays;
import java.util.Scanner;
public class Library{
static String title;
static String author;
static int id;
static int copies;
static String date;
static Book[] database = new Book[100];
static Video[] database2 = new Video[100];
static Journal[] database3 = new Journal[100];
static CD[] database4 = new CD[100];
static int count=0;
public static void main(String[] args){
int i;
Scanner s = new Scanner(System.in);
do{
System.out.println("type the adjacent number to preform that process.\n1: Add an item\n2: Checkout an item\n0: Exit program");
i=s.nextInt();
switch(i){
case 1:
addItem();
break;
case 2:
break;
}
}while(i != 0);
database[0].viewDetails();
database[1].viewDetails();
checkingOut();
database[0].viewDetails();
database[1].viewDetails();
}
public static void addItem(){
int i;
Scanner s = new Scanner(System.in);
do{
System.out.println("type the adjacent number to add the item.\n1: Book\n2: Video\n3: Journal\n4: CD\n Type 0 to stop");
i=s.nextInt();
switch(i){
case 1:
addBook();
break;
case 2:
addVideo();
break;
case 3:
addJournal();
break;
case 4:
addCD();
break;
}
}while(i != 0);
}
public static void addBook(){
String title;
String author;
int id;
int copies;
String date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the book you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the book you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the book you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the book you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
Book Book1 = new Book(date, author, copies, id, title);
database[count] = Book1;
count++;
}
public static void addJournal(){
String title;
String author;
int id;
int copies;
String date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the journal you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the author of the journal you want to add to the collection");
author=s.nextLine();
System.out.println("Enter the publishing date of the journal you want to add to the collection");
date=s.nextLine();
System.out.println("Enter the ID number of the journal you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
Journal Journal1 = new Journal(date, author, copies, id, title);
database3[count] = Journal1;
count++;
}
public static void addCD(){
String title;
String art;
String genre;
int id;
int copies;
int date;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the cd you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the artist of the cd you want to add to the collection");
art=s.nextLine();
System.out.println("Enter the release year of the cd you want to add to the collection");
date=s.nextInt();
System.out.println("Enter the genre of the cd you want to add to the collection");
genre=s.nextLine();
System.out.println("Enter the ID number of the cd you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
CD CD1 = new CD(date, copies, id, title, art, genre);
database4[count] = CD1;
count++;
}
public static void addVideo(){
String title;
String director;
int id;
int copies;
int date;
String genre;
int count=0;
Scanner s = new Scanner(System.in);
System.out.println("Enter the title of the video you want to add to the collection");
title=s.nextLine();
System.out.println("Enter the director of the cd you want to add to the collection");
director=s.nextLine();
System.out.println("Enter the release year of the cd you want to add to the collection");
date=s.nextInt();
System.out.println("Enter the genre of the video you want to add to the collection");
genre=s.nextLine();
System.out.println("Enter the ID number of the video you want to add to the collection");
id=s.nextInt();
System.out.println("Enter the the number of copies that will be added into the collection");
copies=s.nextInt();
Video Video1 = new Video(date, copies, id, title, director, genre);
database2[count] = Video1;
count++;
}
public static void checkingOut(){
boolean found=false;
int idSearch;
int i=0;
Scanner s=new Scanner(System.in);
System.out.println("Enter the ID number of the book you want to check out");
idSearch=s.nextInt();
while(i<database.length && found!=true){
if(database[i].getIdentificationNumber() == idSearch){
found = true;
break;
}
i++;
}
if(found==true){
database[i].checkOut();
System.out.println("There are "+database[i].getNumberCopies()+" copies left");
}
else{System.out.println("There is no book with that ID number!");}
}
}
You could check the type and cast it to that type to gain access to the additional methods.
public static void main(String args[]){
for(Item item : itemList){
if(item instanceof Book){
Book book = (Book) item;
book.someBookMethod();
}
}
}
though using instanceof is considered harmful
A better design would be to make Item abstract and create the methods common to all children, such as add()
public abstract class Item{
public void add();
public void viewDetails();
}
class Book extends Item{
public void add(){
//fun stuff
}
public void viewDetails(){
//moar serious business logic
}
}
....
public static void main(String args[]){
for(Item item : itemList){
item.add();
}
}