This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Java null pointer exceptions - don't understand why…
MOVIE.JAVA
package javaPractical.week3;
import javax.swing.*;
public class Movie {
// private attributes
private String title;
private String movieURL;
private String year;
private String genre;
private String actor;
// constructor
Movie(String t, String u, String y, String g, String a) {
this.title = t;
this.movieURL = u;
this.year = y;
this.genre = g;
this.actor = a;
}
// getters and setters
public void setTitle(String t) {
this.title = t;
}
public String getTitle() {
return this.title;
}
public void set_url(String a) {
this.movieURL = a;
}
public String get_url() {
return this.movieURL;
}
public void setYear(String y) {
this.year = y;
}
public String getYear() {
return this.year;
}
public void setGenre(String g) {
this.genre = g;
}
public String getGenre() {
return this.genre;
}
public void setActor(String a) {
this.actor = a;
}
public String getActor() {
return this.actor;
}
// output movie details
public String toString() {
return ("Title: " + this.title + "\nURL: " + this.movieURL + "\nYear: "
+ this.year + "\nGenre: " + this.genre + "\nActor: " + this.actor);
}
public static void main(String[] args) {
// testing Movie class
Movie Movie1 = new Movie("Spiderman", "www.", "2002", "Action",
"Tobey M");
JOptionPane.showMessageDialog(null, Movie1.toString());
// testing MovieList class
}
}
MOVIELIST.JAVA
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
public class MovieList1 {
private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
private static int NUM_OF_MOVIES = 10;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies() {
return this.myFavouriteMovies.size();
}
public boolean isEmpty() {
if (this.myFavouriteMovies.isEmpty()) {
return true;
} else
return false;
}
public static void main(String[] args) {
MovieList1 List = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
myFavouriteMovies.add(TempMovie);
}
}
You have defined static attribute private static ArrayList<Movie> myFavouriteMovies = new ArrayList();
But in the constructor you are assigning the null. After that you are invoking calls like myFavouriteMovies.size() which causes NullPointerException
public MovieList1() {
this.myFavouriteMovies = null;
this.numberOfMovies = 0;
this.index = 0;
}
Of course it crashes - you've set it to null.
Why on earth didn't you heed the perfectly good advice you received here?
Java null pointer exceptions - don't understand why
You're wasting everyone's time on a trivial question. I'm voting to close.
Try this - it's still heinous, but it runs:
package javaPractical.week3;
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class MovieList1
{
private static int NUM_OF_MOVIES = 10;
private List<Movie> myFavouriteMovies;
private int numberOfMovies = 0;
private int index = 0;
public MovieList1()
{
this.myFavouriteMovies = new ArrayList<Movie>();
this.numberOfMovies = 0;
this.index = 0;
}
public int getNumberOfMovies()
{
return this.myFavouriteMovies.size();
}
public boolean isEmpty()
{
return this.myFavouriteMovies.isEmpty();
}
public void add(Movie movie)
{
this.myFavouriteMovies.add(movie);
}
#Override
public String toString()
{
return "MovieList1{" +
"myFavouriteMovies=" + myFavouriteMovies +
'}';
}
public static void main(String[] args)
{
MovieList1 movieList = new MovieList1();
String titleADD;
String movieURLADD;
String yearADD;
String genreADD;
String actorADD;
titleADD = JOptionPane.showInputDialog(null, "Enter title:");
movieURLADD = JOptionPane.showInputDialog(null, "Enter URL:");
yearADD = JOptionPane.showInputDialog(null, "Enter year:");
genreADD = JOptionPane.showInputDialog(null, "Enter genre:");
actorADD = JOptionPane.showInputDialog(null, "Enter actor:");
Movie TempMovie = new Movie(titleADD, movieURLADD, yearADD, genreADD,
actorADD);
// crashes here
movieList.add(TempMovie);
System.out.println(movieList);
}
}
class Movie
{
private String title;
private String url;
private String year;
private String genre;
private String actor;
Movie(String title, String url, String year, String genre, String actor)
{
this.title = title;
this.url = url;
this.year = year;
this.genre = genre;
this.actor = actor;
}
#Override
public String toString()
{
return "Movie{" +
"title='" + title + '\'' +
", url='" + url + '\'' +
", year='" + year + '\'' +
", genre='" + genre + '\'' +
", actor='" + actor + '\'' +
'}';
}
}
Related
The question wants me to do:
An array of Finance called financeRecord to store the details
of the payments for each semester.
This is my code
package lab5;
class Student_U extends Student {
public String student_name;
private String studentID;
public int student_age;
private byte currentSemester;
private byte TotalFinanceRecord;
private String cohort;
public Student_U() {
student_name = " ";
studentID = " ";
student_age = 0;
currentSemester = 1;
TotalFinanceRecord = 0;
cohort = " ";
}
public Student_U(String student_name, String studentID, int student_age,
String course, String year,
String section, String subject, String student_name2,
String studentID2, int student_age2,
byte currentSemester, byte totalFinanceRecord, String cohort) {
super(student_name, studentID, student_age, course, year,
section, subject);
student_name = student_name2;
studentID = studentID2;
student_age = student_age2;
this.currentSemester = currentSemester;
TotalFinanceRecord = totalFinanceRecord;
this.cohort = cohort;
}
public String getStudent_name() {
return student_name;
}
public void setStudent_name(String student_name) {
this.student_name = student_name;
}
public String getStudentID() {
return studentID;
}
public void setStudentID(String studentID) {
this.studentID = studentID;
}
public int getStudent_age() {
return student_age;
}
public void setStudent_age(int student_age) {
this.student_age = student_age;
}
public byte getCurrentSemester() {
return currentSemester;
}
public void setCurrentSemester(byte currentSemester) {
this.currentSemester = currentSemester;
}
public byte getTotalFinanceRecord() {
return TotalFinanceRecord;
}
public void setTotalFinanceRecord(byte totalFinanceRecord) {
TotalFinanceRecord = totalFinanceRecord;
}
public String getCohort() {
return cohort;
}
public void setCohort(String cohort) {
this.cohort = cohort;
}
public void initStudent() {
}
public void print() {
System.out.print("Student name: " + student_name + " ");
System.out.print("\nMatric No: " + studentID + " ");
System.out.print("\nAge: " + student_age + " ");
System.out.print("\nCurrent Semester: " + currentSemester + " ");
System.out.print("\nCohort: " + cohort + " ");
System.out.println();
}
}
Please help me fix my code I would appreciate it so much.
This is my lab assignment which needs to be submitted by tomorrow.
You could try this, but it's also better to review standard java concepts (arrays, classes, etc). After, just adapt your code as suitable.
public class Finance extends Student
{
public static void main(String args[])
{
Finance f1 = new Finance("Student_1");
System.out.println(f1);
f1.setPayment(1, 10);
System.out.println(f1);
f1.setPayment(2, 10.77);
System.out.println(f1);
Student s2 = new Student("Student 2");
Finance f2 = new Finance(s2);
f2.setPayment(2, 88.77);
System.out.println(f2);
}
Double finaceRecord[] = new Double[3];
private void initPayment()
{
for(int i=0;i<finaceRecord.length;i++)
{
finaceRecord[i]=0.0;
}
}
public Finance(Student s)
{
super(s.name);
initPayment();
}
public Finance(String name)
{
super(name);
initPayment();
}
//store first or second
public void setPayment(int i, double d)
{
if(d<=0) return;
if(i==1)
{
finaceRecord[i] = d;
}
else
{
finaceRecord[2] = d;
}
finaceRecord[0] = finaceRecord[2] + finaceRecord[1];
}
public String toString()
{
return "name="+super.name+", Total Paid="+finaceRecord[0]+","
+ " Sem1="+finaceRecord[1]+", Sem2="+finaceRecord[2];
}
}
...
public class Student
{
String name;
int Semester;
Student(String name)
{
this.name = name;
this.Semester = 1;
}
}
Ouptut
name=Student_1, Total Paid=0.0, Sem1=0.0, Sem2=0.0
name=Student_1, Total Paid=10.0, Sem1=10.0, Sem2=0.0
name=Student_1, Total Paid=20.77, Sem1=10.0, Sem2=10.77
name=Student 2, Total Paid=88.77, Sem1=0.0, Sem2=88.77
from what I understand you are supposed to create an array of Finance type
Finance []financeRecord = new Finance[totalFinanceRecord];
and then you can access the values of Finance class
financeRecord[indexNumber].methodName();
I have made a Note class where i want to increment the id. It is not getting incremented. And also i am taking input description from console . how to accept a lengthy description like("This is Hello World") in java from the user.Please help.
public class Note {
private String title;
private static int id;
private static int count = 0;
private String description;
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Note Console class that accepts input from the user. It accepts 1. Add Note where in i want to accept a proper description from the user. Second View note where with the help of toString method i print the output. Third is EXIT
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
NoteServiceSerialize service1 = new NoteServiceSerialize();
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
Scanner in = new Scanner(System.in);
int choice = in.nextInt();
while (!loop) {
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
String title = in.next();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.next();
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
//code
}
}
}
}
public static void main(String[] args) {
NoteConsole();
}
}
NoteServiceSerialize class -
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class NoteServiceSerialize {
public void noteSerialize (ArrayList<Note> list){
try{
FileOutputStream file = new FileOutputStream("D:\\serializable_notes.txt");
ObjectOutputStream obj = new ObjectOutputStream(file);
obj.writeObject(list);
file.close();
obj.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
Make id instance variable and increase count in constructor of class and assign current value of count to the id
public class Note {
private String title;
private int id;
private static int count = 0;
private String description;
public Note(){
count++;
this.id = count;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription(){
return description;
}
public void setDescription(String description){
this.description=description;
}
public String toString() {
return ("Id : " + id + "\n Title :" + title + "\n Description :"+ description);
}
}
Now every Note object will have separate id.
public class NoteConsole {
//NoteConsole() is not constructor, should avoid same method name and class name
public static void NoteConsole() {
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = true;
//NoteConsole nc = new NoteConsole();
Note note = new Note();
ArrayList<Note> notes = new ArrayList<Note>();
//NoteServiceSerialize service1 = new NoteServiceSerialize();
Scanner in = new Scanner(System.in);
while (loop) {
System.out.println("Write to the Console 1.AddNote, 2. ToView 3. Exit");
int choice = in.nextInt();
in.nextLine();
switch (choice) {
case ADD_NOTE: {
System.out.println("Enter the title");
//in.nextLine() will read complete line.
String title = in.nextLine();
note.setTitle(title);
System.out.println("Enter the description");
String description = in.nextLine();
note.setDescription(description);
notes.add(note);
//service1.noteSerialize(notes);
break;
}
case VIEW_NOTE: {
for (Note note1 : notes) {
System.out.println(note1);
}
break;
}
case EXIT: {
loop = false;
}
}
}
in.close();
}
public static void main(String[] args) {
NoteConsole();
}
First you should provided the NoteServiceSerialize class too.
for your description problem you should use a in.nextLine() .
and about increment id, doing that in getTitle() is a bad practice.
a better alternative is this way:
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
and your classes had some other problems too, replace them with this:
public class Note {
private String title;
private String description;
private static int lastId;
private int id = nextId();
private static int nextId() {
lastId = ++lastId;
return lastId;
}
public static int getLastId() {
return lastId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public void setTitle(String description) {
this.description = description;
}
#Override
public String toString() {
return ("Id : " + id + "\nTitle :" + title + "\nDescription :" + description);
}
}
import java.util.ArrayList;
import java.util.Scanner;
public class NoteConsole {
final static ArrayList<Note> notes = new ArrayList<Note>();
public static void NoteConsole() {
NoteServiceSerialize service1 = new NoteServiceSerialize();
NoteConsole nc = new NoteConsole();
Note note = new Note();
final int ADD_NOTE = 1;
final int VIEW_NOTE = 2;
final int EXIT = 3;
boolean loop = false;
Scanner in = new Scanner(System.in);
while (!loop) {
System.out.println("Write to the Console 1.AddNote 2. ToView 3. Exit");
int choice = in.nextInt();
switch (choice) {
case ADD_NOTE:
System.out.println("Enter the title :");
String title = in.next();
System.out.println("Enter the description :");
//if you had a problem with description text remove in.next()
in.next();
String description = in.nextLine();
note.setTitle(title);
note.setDescription(description);
notes.add(note);
service1.noteSerialize(notes);
System.out.println("----------------------");
break;
case VIEW_NOTE:
for (Note note1 : notes) {
System.out.println(note1);
System.out.println("----------------------");
}
break;
case EXIT:
loop = !loop;
break;
default:
System.out.println("Not a Valid Option !!!");
}
System.out.println();
}
}
public static void main(String[] args) {
NoteConsole();
}
}
id would remain 0 (default value of primitive) unless your one of the method is called :
public static int getId() {
return id = ++count;
}
public String getTitle() {
id++;
return title;
}
where you actually increment the value of id. Maybe something like :
public String toString() {
return ("Id : " + getId() + "\n Title :" + title + "\n Description :"+ description);
}
Also make sure your count is initialized as :
private static final int count = 0;
I have a method that is supposed to replenish stock parts for a manufacturer. I have tried using super.Method() but its not working. There's also a class called Part if it's needed.
Main Class
package main;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class TestAssembledPart {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
List<AssembledPart> aparts = new ArrayList<AssembledPart>();
aparts.add(new AssembledPart("a200", "Crank & Pedal", 10, 3.5, "Crank", "Pedal"));
System.out.println("part before stock level change - start");
System.out.println(AssembledPart.toAssembledString(aparts));
for (AssembledPart apart: aparts){
if(apart!=null){
System.out.println("Please enter replenish quantity");
aparts.replenish(sc.nextInt());
}
}
System.out.println("part before stock level change - end");
System.out.println(AssembledPart.toAssembledString(aparts));
}
}
AssembledPart Class
package main;
import java.util.*;
public class AssembledPart extends Part {
private String basica;
private String basicb;
private int assembledstocklevel;
public AssembledPart(String id, String name, int stocklevel, double unitprice,
String basica, String basicb) {
super(id, name, stocklevel, unitprice);
this.basica = basica;
this.basicb = basicb;
}
public void replenish(int qty){
super.replenish(qty);
//super.stocklevel = super.stocklevel + qty;
}
public String toAssembledString() {
return super.toString() + " | " + basica + " | " + basicb;
}
public static String toAssembledString(Collection<AssembledPart> aparts){
String s = "";
for (AssembledPart apart: aparts){
s += apart.toAssembledString() + "\n";
}
return s;
}
}
PartClass
package main;
import java.util.*;
public class Part {
private String id;
private String name;
protected int stocklevel;
private double unitprice;
private int qty = 6000;
public Part(String id, String name, int stocklevel, double unitprice){
this.id = id;
this.name = name;
this.stocklevel = stocklevel;
this.unitprice = unitprice;
}
String partsAvailable()
{
//String newLine = System.getProperty("line.separator");
return (id + "\t" + name + "\t " + stocklevel + "\t\t " + unitprice);
}
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStockLevel(){
return stocklevel - qty;
}
public void setStockLevel(int stocklevel){
this.stocklevel = stocklevel;
}
public double getUnitPrice(){
return unitprice;
}
public void setUnitPrice(double unitprice){
this.unitprice = unitprice;
}
public void replenish(int qty){
this.stocklevel = stocklevel + qty;
}
public double supply(int qty){
return unitprice * qty;
}
public String toString() {
return id + " | " + name + " | " + stocklevel + " | " + unitprice;
}
public static String toString(Collection<Part> parts){
String s = "";
for (Part part: parts){
s += part + "\n";
}
return s;
}
}
Replace this line :
aparts.replenish(sc.nextInt());
With the following
apart.replenish(sc.nextInt());
You were actually calling a method on the collection that contains your objects instead of the objects themself.
i have this assignment where i am suppose to print all in one dialog box the book title, isbn number, and charge for all 5 books. I am having trouble doing that in my for loop. i get an error with the current code when trying to get the book title from my toString saying non static variable cannot be referenced from a static context but i think its because im not calling it right.
public class Book
{
private String title;
private String author;
private String isbn;
private Double price;
private Publisher publisher;
public Book()
{
setTitle("");
setAuthor("");
setIsbn("");
setPrice(0.0);
setPublisher(new Publisher());
}
public Book(String t, String a, String i, double p, Publisher n)
{
setTitle(t);
setAuthor(a);
setIsbn(i);
setPrice(p);
setPublisher(n);
}
public void setTitle(String t)
{
title = t;
}
public String getTitle()
{
return title;
}
public void setAuthor(String a)
{
author = a;
}
public String getAuthor()
{
return author;
}
public void setIsbn(String i)
{
isbn = i;
}
public String getIsbn()
{
return isbn;
}
public void setPrice(double p)
{
price = p;
}
public double getPrice()
{
return price;
}
public void setPublisher(Publisher n)
{
publisher = n;
}
public Publisher getPublisher()
{
return publisher;
}
public double calculateTotal(int quantity)
{
return(price * quantity);
}
public String toString()
{
return( " Title " + title + " Author " + author + " Isbn " + isbn
+ " Price " + price + " Publisher " + publisher.toString());
}
}
import javax.swing. JOptionPane;
public class BookTest
{
public static void main(String args[])
{
double charge;
String dataArray[][] = {{"Abraham Lincoln Vampire Hunter","Grahame-Smith","978-0446563079","13.99", "Haper", "NY"},
{"Frankenstein","Shelley","978-0486282114","7.99","Pearson", "TX"},
{"Dracula","Stoker","978-0486411095","5.99","Double Day", "CA"},
{"Curse of the Wolfman"," Hageman","B00381AKHG","10.59","Harper", "NY"},
{"The Mummy","Rice","978-0345369949","7.99","Nelson", "GA"}};
Book bookArray[] = new Book[dataArray.length];
int quantityArray[] = {12, 3, 7, 23, 5};
for (int i = 0; i < dataArray.length; i++)
{
bookArray[i] = new Book(dataArray[i][0], dataArray[i][1], dataArray[i][2],
Double.parseDouble(dataArray[i][3]), new Publisher(dataArray[i][4], dataArray[i][5]));
}
String msg = " ";
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
msg += String.format("Title ", this.getTitle()); //stuff to print
}
JOptionPane.showMessageDialog(null, msg);
}
}
You want to do:
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
msg += String.format("Title ", bookArray[i].getTitle());
}
You are getting the title of a particular book (referenced by bookArray[i])
I think it might be an issue with this line:
msg += String.format("Title ", this.getTitle()); //stuff to print
try this:
for (int i = 0; i < bookArray.length; i++)
{
charge = bookArray[i].calculateTotal(quantityArray[i]);
msg += String.format("Title %s", bookArray[i].getTitle()); //stuff to print
}
Is it possible to sort two class arrays that have a common string type variable alphabetically in java? I have a parent and child classes, each set as an array and I want to sort them alphabetically based on a variable that is in the parent class, like a title. I am fairly new to java and want to know if there anything that can accomplish this in java. Thanks in advance for the help.
import java.util.Scanner;
import java.lang.reflect.Array;
import java.text.NumberFormat;
import java.util.Locale;
//declaration of class Bookstore
public class Bookstore
{
// main method begins execution of program
public static void main (String [] agrs)
{
//declare and set variables
double price = 0.0;
int year = 0;
String isbn = "";
String publisher = "";
String author = "";
String title = "";
String website = "";
double value = 0.0;
double sum = 0;
// create Scanner to obtain user input
Scanner input = new Scanner(System.in);
//create a format for currency
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
//construct the Book object as an array
Book[] bk = new Book[3];
EBook[] ebk = new EBook[2];
//for loop to distinguish between the Book array elements
for (int i = 0; i <bk.length; i++)
bk[i] = new Book (title, price, year, publisher, author, isbn);
//for loop to distinguish between the EBook array elements
for (int i = 0; i <ebk.length; i++)
ebk[i]= new EBook(isbn, price, year, publisher, author, title, website);
//set values for variables in the Book class array
bk[0].setIsbn("9780345917430");
bk[0].setTitle("Lord of the Rings");
bk[0].setAuthor("J. R. R. Tolkien");
bk[0].setYear(1954);
bk[0].setPublisher("Allen & Unwin");
bk[0].setPrice(10.75);
bk[1].setIsbn("0747532699");
bk[1].setTitle("Harry Potter");
bk[1].setAuthor("J. K. Rowling");
bk[1].setYear(1998);
bk[1].setPublisher("Scholastic Press");
bk[1].setPrice(14.12);
//calculate value of Book class
for (int i = 0; i <bk.length; i++)
value += bk[i].getPrice();
//calculate value of Book class
for (int i = 0; i <ebk.length; i++)
sum+= ebk[i].getPrice();
//calculate value of entire inventory
for (int i = 0; i <ebk.length; i++)
value = value + sum - ebk[i].getDiscount();
//display results
for (int i = 0; i <bk.length; i++)
System.out.println(bk[i].toString());
for (int i = 0; i <ebk.length; i++)
System.out.println(ebk[i].toString());
//display total value of inventory
System.out.println("Total inventory: " + nf.format(value));
}
}
class Book
{
//define variables
private String isbn;
private double price;
private String publisher;
private String author;
private String title;
private int year;
//constructor that initializes fields
public Book(String title, double price, int year, String publisher, String author, String isbn)
{
this.isbn = isbn;
this.price = price;
this.publisher = publisher;
this.author = author;
this.title = title;
this.year = year;
}
//empty constructor
public Book()
{
this("", 0.0, 0, "", "", "");
}
//set ISBN
public void setIsbn(String isbn)
{
this.isbn = isbn;
}
//get ISBN
public String getIsbn() {
return this.isbn;
}
//set price
public void setPrice(double price)
{
this.price = price;
}
//get price
public double getPrice()
{
return this.price;
}
//set year
public void setYear(int year)
{
this.year = year;
}
//get year
public int getYear()
{
return this.year;
}
//set publisher
public void setPublisher(String publisher)
{
this.publisher = publisher;
}
//get publisher
public String getPublisher()
{
return this.publisher;
}
//set author
public void setAuthor(String author)
{
this.author = author;
}
//get author
public String getAuthor()
{
return this.author;
}
//set title
public void setTitle(String title)
{
this.title = title;
}
//get title
public String getTitle()
{
return this.title;
}
//display results
public String toString()
{
//create a format for currency
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
return "ISBM number: " + this.isbn + "\n" +
"Title: " + this.title + "\n" +
"Author's name: " + this.author + "\n" +
"Year published: " + this.year + "\n" +
"Publisher's name: " + this.publisher + "\n" +
"Sale price: " + nf.format(this.price) + "\n" +
"\n-----------------------------------------------------------------------\n";
}
}
class EBook extends Book
{
//define variable
private String website;
public EBook(String title, double price, int year, String publisher, String author, String isbn, String website)
{
super(title, price, year, publisher, author, isbn);
this.website = website;
}
//empty constructor
public EBook()
{
this.website = "";
}
//get website
public String getWebsite()
{
return website;
}
//set website
public void setWebsite(String website)
{
this.website = website;
}
//set discount
public double getDiscount()
{
return super.getPrice() * 0.10;
}
#Override
public String toString() {
//create a format for currency
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
return "ISBN number: " + super.getIsbn() + "\n" +
"Title: " + super.getTitle() + "\n" +
"Author's name: " + super.getAuthor() + "\n" +
"Year published: " + super.getYear() + "\n" +
"Publisher's name: " + super.getPublisher() + "\n" +
"Sale price: " + nf.format(super.getPrice()) + "\n" +
"Website: " + this.website + "\n" +
"Discount: " +nf.format(super.getPrice() * 0.10) + "\n" +
"\n-----------------------------------------------------------------------\n";
}
}
Yes that is doable. Just try implementing Comparable interface for Base class that is Book class only.
class Book implements Comparable<Book> {
// Your Rest of the code...
// Rest of the code ...
#Override
public int compareTo(Book o) {
if(o == null) {
return 1;
}
if (this == o) {
return 0;
} else {
if(this.title != null && o.title != null) {
return this.title.compareTo(o.title);
} else if(this.title != null) {
return 1;
} else {
return -1;
}
}
}
}
And to sort the array use
Arrays.sort(bk);
Hope it helps you :)