I'm trying to read this text file - java

I made a two classes, one text file, and a code that should print everything out, but it still becomes null no matter what I do? I'm trying to read the code from the text file by using the toString method from the Book class and the printInventory from the Inventory class in the InventoryTester.
My first code derives on what should be printed. I made a constructor and I used setters and getters to make this. Then ended it with a toString() method. I made a Book class that should print everything to the printInventory in the InventoryTester.
Book class:
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.lang.*;
public class Book {
// Initiate variables
// Note: I used the DecimalFormat so every price is always going to have 2 decimal spaces
private static DecimalFormat df2 = new DecimalFormat("#.##");
private String ISBN;
private String author;
private String title;
private int edition;
private String pubCode;
private int quantity;
private double price;
//constructor
public Book(String isbn, String auth, String ti, int ed, String pc, int qty, double pr)
{
ISBN = isbn;
author = auth;
title = ti;
edition = ed;
pubCode = pc;
quantity = qty;
price = pr;
}
//getters
public String getTitle(){return title;}
public String getAuthor(){return author;}
public double getPrice(){return price;}
public int getEdition(){return edition;}
public String getISBN(){return ISBN;}
public String getpubCode(){return pubCode;}
public int getQuantity(){return quantity;}
//setters
public void changePrice(double newPrice){price = newPrice;}
public boolean changeQuantity(int changeAmt){
changeAmt = quantity + changeAmt;
if (changeAmt < 0) {
return false;
}
else {
return true;
}
}
//This prints out all of the information once the object 'Book' is used
public String toString()
{
String subAuthor = "";
String subTitle = "";
subAuthor = author.substring(0,16);
subTitle = title.substring(0,32);
return "ISBN: " +ISBN + "\nAuthor: " + subAuthor + "\nTitle: " + subTitle + "\nEdition: " + edition + "\nPublisher Code: " + pubCode +"\nQuantity: " +quantity+ "\nPrice: $ " +df2.format(price) + "\n\n";
}
}
Then I made a class called Inventory to manage instances of the Book class. However, I'm still not sure if most of my code is correct since I compiled it without any errors. What I mean is the constructor itself, the addBook method and the changeQuantity method.
The constructor takes one argument, which is the size of the books array. It should create the empty array of the specified size, and initializes the nextEntry field to be 0. I use the printInventory method here. This method should print the entire inventory from the Book class, using the toString()method on each book.
Inventory class:
import java.math.RoundingMode;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.util.Arrays;
public class Inventory {
private Book[] books;
private int nextEntry;
int questionAmt;
public Inventory(int size){
size = 7;
books = new Book[size];
nextEntry = 0;
}
public boolean addBook(Book theBook) {
if (nextEntry > 27)
{ return false;}
else{
nextEntry++;
books[nextEntry] = theBook;
return true;
}
}
public boolean changeQuantity(String isbn, int changeAmt) {
if (changeAmt < 0) {
return false;
}
else {
return true;
}
}
public void printInventory()
{
for (int i=0; i<books.length; i++) {
System.out.println(books[i].toString());
return;
}
}
Then I added the text file, which is called inventory. This is what should be shown in the code and I should be able to edit the quantity it inside the console. I also added a 28 because it needs 28 Books.
inventory.txt:
28
013478796X_Tony Gaddis_Starting Out with Java: From Control Structures through Data Structures_4_PE_10_121.75
0321409493_John Lewis_Java Software Solutions: Foundations of Program Design_5_AW_12_94.05
0023606924_Richard Johnsonbaugh_Algorithms_1_PH_1_109.00
0134743350_Harvey Dietel_Java: How to Program, Early Objects_12_PE_12_134.84
0131474340_Ralph Morelli_Java, Java, Java, Object-Oriented Problem Solving_3_PH_4_95.25
0596100469_Alex Martelli_Python in a Nutshell_2_OR_6_39.99
0134802217_Tony Gaddis_Starting Out with Java: From Control Structures through Objects_7_PE_8_118.67
1403946876_Sally Fincher_Studying Programming_1_PM_3_26.59
0596510047_Andy Oram_Beautiful Code: Leading Programmers Explain How They Think_1_OR_5_44.99
0143037889_Ray Kurzweil_The Singularity is Near: When Humans Transcend Biology_1_PG_20_17.70
0135205972_John Lewis_Java Foundations: Introduction to Program Design and Data Structures_5_PE_5_129.99
0131872893_Wanda Dann_Learning to Program with Alice_1_PH_12_47.50
159413962X_Dave Eggers_The Circle_1_AW_4_3.99
1887902996_John Zelle_Python Programming: An Introduction to Computer Science_1_FB_2_26.40
0133356728_Rafael Gonzales_Digital Image Processing_4_PE_3_248.17
1592400876_Lynne Truss_Eats, Shoots & Leaves_1_PG_5_17.70
0072823798_William Collins_Data Structures and the Java Collections Framework_2_MH_6_105.57
0072866098_Allen Tucker_Programming Languages: Principles and Paradigms_2_MH_1_127.50
0534950973_Michael Sipser_Introduction to the Theory of Computation_2_CT_3_98.90
0131496710_Francis Hill_Computer Graphics Using OpenGL 3rd Edition_3_PH_4_112.00
0321173486_Dave Shreiner_OpenGL Programming Guide_5_AW_1_24.00
0072865512_Steven Schach_Object Oriented and Classical Software Engineering_6_MH_9_123.44
0321228383_Michael Kifer_Database Systems: An Application-Oriented Approach_2_AW_3_112.86
1416587787_Cliff Stoll_The Cuckoo's Egg_1_PG_3_13.32
1400032717_Mark Haddon_The Curious Incident of the Dog in the Night-Time_1_VI_10_13.95
006025492X_Maurice Sendak_Where the Wild Things Are_1_HC_6_17.95
0694003611_Margaret Brown_Goodnight Moon_1_HC_138_8.99
069401298X_Arnold Lobel_Frog and Toad Together_1_HC_27_11.55
Last, but not least, I made an InventoryTester file to read the text file and print it using the code from both classes.
InventoryTester:
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import java.awt.Font;
import java.util.Scanner;
import java.io.*;
public class InventoryTester {
public static void main(String[] args) throws IOException {
Scanner inFile= new Scanner(new File("inventory.txt"));
Book books;
String inLine= inFile.nextLine();
int size= Integer.parseInt(inLine);
Inventory myInventory= new Inventory(size);
while (inFile.hasNext()) {
inLine= inFile.nextLine();
String ISBN = inFile.next();
String author = inFile.next();
String title = inFile.next();
int edition = inFile.nextInt();
String pubCode = inFile.next();
int quantity = inFile.nextInt();
double price = inFile.nextDouble();
myInventory.addBook(new Book(ISBN, author, title, edition, pubCode, quantity, price));
String[] tokens = inLine.split("_");
myInventory.printInventory();
}
inFile.close();
}
}
I was trying to make Java understand that there are strings, ints, and doubles. I'm trying to convert the text file using arrays into Strings, ints, and doubles. It should print, but the code considers it to be null. Am I missing something?
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Book.toString()" because "this.books[i]" is null
at Inventory.printInventory(Inventory.java:42)
at InventoryTester.main(InventoryTester.java:28)
----jGRASP wedge2: exit code for process is 1.

You could make a class to manage your inventory with an arraylist containing books. And then save that class in a binary file.
The class could look like this:
public class BookList implements Serializable
{
private ArrayList<Book> books;
public BookList()
{
books = new ArrayList<>();
}
public void addBook(Book book)
{
this.books.add(book);
}
public void removeBook(Book book)
{
this.books.remove(book);
}
public ArrayList<Book> getAllBooks()
{
return books;
}
And then save and load the file like this.
File file = new File("inventory.bin")
public void save(BookList bookList){
FileOutputStream out = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(bookList);
}
public BookList load(){
BookList bookList = null;
FileInputStream in = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(in);
bookList = (BookList) ois.readObject();
in.close();
ois.close();
}
Then you shouldn't have any trouble reading from the file.
REMEMBER! Both the list class and book class needs to implement Serializable.

Related

adding into an Array list of objects from a text file in java

i thinkj i have a type argument problem which im really confused about, Ive started with an Arraylist which, extends to the another class with my main methods. and i have a Events class, which i want to categorize from the txt file, the main problem i have is adding from my txt file which iread into an ArrayList, java pops up with this error message
incompatible types: java.lang.String cannot be converted to CSC8012.Events
But in my events it has String? Im really confused
This is my generic arraylist i think?
import java.util.ArrayList;
public class SortedArrayList<E extends Comparable> extends
ArrayList<E> {
public void insert(E e) {
this.add(e);
int lastIndex = 0;
for( lastIndex = this.size() -1 ; lastIndex > 0 && this.get(lastIndex-1).compareTo(e) > 0 ; lastIndex--){
this.set(lastIndex, this.get(lastIndex-1));
}
this.set(lastIndex,e);
}
}
Heres my events class objects
public class Events implements Comparable<Events>{
//fields setting up the variables
String ticketsbought;
String eventname;
public Events(String ticketsbought, String eventname ){
this.ticketsbought = ticketsbought;
this.eventname = eventname;
}
#Override
public int compareTo (Events E){
return
ticketsbought.compareTo(E.getTicketsbought()) + eventname.compareTo(E.getEventname());
}
public String getTicketsbought() {
return ticketsbought;
}
public String getEventname() {
return eventname;
}
//setting it up for the main method from the constructor fields above
public void setTicketsbought(String ticketsbought) {
this.ticketsbought = ticketsbought;
}
public void setEventname(String eventname) {
this.eventname = eventname;
}
#Override
public String toString()
{
return "Tickets bought " + this.ticketsbought + "Event name " + this.eventname;
}
}
My main menu class
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Objects;
import java.util.ArrayList;
import java.util.Collections;
java.util.Scanner;
public class MainProgram extends SortedArrayList{
public static void main(String[] args) throws FileNotFoundException{
boolean bye = false;
String line;
String option;
Scanner sc = new Scanner(System.in); //tos take in our input
do{
System.out.println("Choose an option.."); // heres our options
System.out.println("e Information on all events");
System.out.println("c All information on clients");
System.out.println("f to quit");
System.out.println("b to update when tickets are bought by a registered Client");
System.out.println("r to update the stored data when a Client cancels a ticket");
option = sc.nextLine();
switch (option) { // these are splitting our inputs to these cases with different outcomes
case "e":
//System.out.println("information on events");
Scanner inFile = new Scanner(new FileReader("input.txt"));
// Other declarations// Reading and processing the input data// Printing out the results outFile.close();
ArrayList<Events> events = new ArrayList<>();
while(inFile.hasNextLine()) {
String data = inFile.next();
events.add(data);//error based on these? Event is based off of arraylist<E> and inherits from those whilst i have them as string?
You are seeing the exception because of Generics in Java.
Your ArrayList is declared to take Events objects.
ArrayList<Events> events = new ArrayList<>();
However, you are trying to add a String object to it.
String data = inFile.next();
events.add(data); //Cannot add a String object, only Events object allowed.
One way to fix this is to create an Events object using the String, and then add to the Arraylist. I am assuming each line has Event name and String in it, separated by a comma.
//Get your event name and tickets from the String data.
String tokens[] = data.split(",");
String eventName = tokens[0];
String ticketsBought = tokens[1];
//create an events object
Events eventObj = new Events(eventName, ticketsBought);
//Now add to your arraylist.
events.add(eventObj);
As an aside, you do not need to extend SortedArrayList in MainProgram. The main class is usually top level class in your project, and it will only contain objects (this is a common practice). If you want to use the new logic you have added in SortedArrayList, then instead of creating ArrayList<Events> events = new ArrayList<>();, you can create SortedArrayList<Events> events = new SortedArrayList<>();

how to print specific lines from an array from another class

So Im trying to print only the novels added to the array and I cant figure out how..
Also I need to return the number of books of a specific kind.
Im new to programming so please take me easy :)
Here is the app, I have to add all the books from console
Each word added from console triggers a specific action so to print the books I need to write print, to add i need to write add , type of book, title of book, author, and so on.
import java.util.*;
public class App{
public static void main(String [] args){
Scanner s = new Scanner(System.in);
Library bib = Library.getInstance();
String line = "";
line = s.nextLine();
String[] v = line.split("\\s+");
while(true){
switch(v[0]){
case "add":
String title = v[2];
String autor = v[3];
Book c = null;
if("story".equals(v[1])){
c = new Story(title, autor);
} else if("novel".equals(v[1])){
int pages = Integer.parseInt(v[4]);
c = new Novel(title, autor, pages);
} else if("poetry".equals(v[1])){
String publish = v[4];
c = new Poetry(title, autor, publish);
}
bib.adauga(c);
break;
case "print" :
case "return" :
case "exit" : System.exit(0); break;
default : System.out.println("Command " + v[0] + " does not exist");
}
}
}
}
import java.util.*;
public class Library{
private static Library instance;
List<Book> books;
private Library(){
books = new ArrayList<>();
}
public static Library getInstance(){
if(instance == null){
instance = new Library();
}
return instance;
}
public void adauga(Book c){
books.add(c);
}
public void afisare(){
for(Book c : books){
System.out.println(c);
}
}
}
public abstract class Book{
String title;
String autor;
public Book(String title, String autor){
this.title=title;
this.autor=autor;
}
#Override
public String toString(){
return title + " " + autor;
}
}
public class Novel extends Book {
int pages;
public Novel(String title, String autor, int pages){
super(title, autor);
this.pages=pages;
}
#Override
public String toString(){
return super.toString() + " " + pages;
}
}
You can use instanceof to check what the type of an object is.
//Go through every book
for(Book book : bib.books){
if(book instanceof Novel){
System.out.println(book);
}
}
You have created a method that print all the books of theLibrary, you need to modify it to print the good type of book :
Use print novel for example :
// in App
case "print" : bib.afisare(v[1]);
break;
// in Library
public void afisare(String type){
for(Book c : books){
if("novel".equals(type) && c instance of Novel)
System.out.println(c);
else if("story".equals(type) && c instance of Story)
System.out.println(c);
else if("poetry".equals(type) && c instance of Poetry)
System.out.println(c);
}
}
Also, because of your while(true) you are going to run in infinite loop, you need to ask again after the switch or don't ask before and use do{}while();
do{
line = s.nextLine();
String[] v = line.split("\\s+");
switch(v[0]){
...
}
}while(true);
You can access variables from other objects by using '.' as long the variable is in visibility (e.g. public or in same package) or you use getter methods.
So in your case you can do something like this.
final List<Book> books = Library.getInstance().getBooks();
for(Book book : books) {
if(book instanceof Novel) {
System.out.println(((Novel)book).toString());
}
}
need to add to Library
public List<Book> getBooks() {
return this.books;
}
This is just a simple example how you can use your books and pages with your example, feel free to edit and use it as you need to.

Adding objects to ArrayList [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
This if my first question on stackoverflow. I can usually find answers myself but I'm having trouble with this one. I've got 2 objects, "Book", and "Periodical". These are subclasses to a class "Publication". Now, I'm trying to add 3 instances of "Book" and 3 instances of "Periodical" to an ArrayList. I'm having trouble figuring out how to do this.
With this current code, I get an error "no suitable method found for add(Book,Book,Book,Periodical,Periodical,Periodical).
Here is the current code:
import java.util.ArrayList;
import java.util.Date;
public class DriverProgram {
public static void main(String[] args) {
// Instantiate 3 instances of each object.
Book book1 = new Book(1234, 1, "James", 100, "Hello", "Berkwood Inc.", new java.util.Date(), "History");
Book book2 = new Book(2345, 2, "Ralph", 200, "Goodbye", "Shackles Co.", new java.util.Date(), "English");
Book book3 = new Book(3456, 3, "Julia", 300, "Hello Again", "Trustin Inc.", new java.util.Date(), "History");
Periodical periodical1 = new Periodical("Daily", "Dylan", "History 101", "History Inc.", new java.util.Date(), "History");
Periodical periodical2 = new Periodical("Weekly", "Jannette", "Mathematics 101", "Mathematics Inc.", new java.util.Date(), "Mathematics");
Periodical periodical3 = new Periodical("Monthly", "Patricia", "Science 101", "Science Inc.", new java.util.Date(), "Science");
// Create an array list of the Publication class type, and add the objects to it.
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
// Pass the array list to a method to loop through it and display the toString methods.
displayObjects(publications);
} // End of main
static void displayObjects (ArrayList<Publication> publications) {
// Loop through array list and display the objects using the toString methods.
for (Publication p : publications) {
System.out.print(p.toString());
} // End of for each loop
} // End of displayObjects
} // End of DriverProgram class
I've also tried changing:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
To this:
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
Which rids my program of the compiler error, but then it just prints the "periodical3" object, 6 times. I'm not sure what I'm doing wrong. Any suggestions? Thank you in advance! :)
EDIT:
Here is my Book class:
public class Book extends Publication{
private static int isbn = 0;
private static int libraryOfCongressNbr = 0;
private static String author = "";
private static int nbrOfPages = 0;
// Constructor for Book class with parameters for each attribute.
public Book(int newISBN, int newLibraryOfCongressNbr, String newAuthor, int newNbrOfPages, String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject) {
super(newTitle, newPublisher, newPublicationDate, newSubject);
isbn = newISBN;
libraryOfCongressNbr = newLibraryOfCongressNbr;
author = newAuthor;
nbrOfPages = newNbrOfPages;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
int getISBN() {
return isbn;
}
int getLibraryOfCongressNbr() {
return libraryOfCongressNbr;
}
String getAuthor() {
return author;
}
int getNbrOfPages() {
return nbrOfPages;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setISBN(int newISBN) {
isbn = newISBN;
}
void setLibraryOfCongressNbr(int newLibraryOfCongressNbr) {
libraryOfCongressNbr = newLibraryOfCongressNbr;
}
void setAuthor(String newAuthor) {
author = newAuthor;
}
void setNbrOfPages(int newNbrOfPages) {
nbrOfPages = newNbrOfPages;
}
//toString method for Book class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nISBN: " + isbn + "\n");
result.append("\nPublisher: " + libraryOfCongressNbr + "\n");
result.append("\nAuthor: " + author + "\n");
result.append("\nNumber of Pages: " + nbrOfPages + "\n");
result.append("--------------------------------------------------------- ");
return super.toString() + result.toString();
} // End of toString
} // End of Book class
My Periodical class is identical, but here is my Publication class:
import java.util.Date;
public abstract class Publication {
// Data fields.
private static String title = "";
private static String publisher = "";
private static java.util.Date publicationDate;
private static String subject = "";
// Constructor for Publication class with parameters for each attribute.
public Publication(String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject){
title = newTitle;
publisher = newPublisher;
publicationDate = newPublicationDate;
subject = newSubject;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
String getTitle() {
return title;
}
String getPublisher() {
return publisher;
}
java.util.Date getPublicationDate() {
return publicationDate;
}
String getSubject() {
return subject;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setTitle(String newTitle) {
title = newTitle;
}
void setPublisher(String newPublisher) {
publisher = newPublisher;
}
void setPublicationDate(java.util.Date newPublicationDate) {
publicationDate = newPublicationDate;
}
void setSubject(String newSubject) {
subject = newSubject;
}
//toString method for Publication class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nTitle: " + title + "\n");
result.append("\nPublisher: " + publisher + "\n");
result.append("\nPublication Date: " + publicationDate + "\n");
result.append("\nSubject: " + subject + "\n");
return result.toString();
} // End of toString
} // End of Publication class
Let me know if you need anything else!
EDIT x2: Sorry, I realize my post is getting quite long.
So I've gotten rid of all "static" keywords from my class variables, or "data fields" as I've called them in my code. I then changed my code back to this code:
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
And it works! It executes as it should! I just one question though, since this code doesn't seem to work:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
Is there a shorter way to add all of the objects to the ArrayList with out doing it one by one?
If I understand the problem correctly, you have 6 Publication objects, and you are only seeing the values of the most recently created one.
That would likely be caused because you have static class variables instead of instance variables.
For example
class A {
static int x; // class variable
int y; // instance variable
public A(int val) {
x = val; // All 'A' classes now have x = val;
y = val; // Only 'this' class has y = val;
}
}
If I were to run this
A a1 = new A(4);
A a2 = new A(5);
System.out.println(a1.x);
Then I would see it print 5 and not 4, which describes the scenario you are seeing because you have assigned all variables in the Publication class to those that you use during the last call of new Periodical.
The solution is to not use static variables if you want to have multiple instances of a class with their own values.

How do I read in comma separated string from text file that is inputted from command-line as argument?

I am writing a program that sorts hospital records. These records come in a text file that the user inputs in the command-line as an argument when they call the class "Patient" that is below. The format of the records for each line in the text file is lastname(string), firstname(string), roomnumber(int),age(int). The number of lines is unknown. The user will specify the file name as the first argument and then specify the field on which to sort.
What I am specifically having trouble figuring out is how to read in the text file and store the information in an array. I have been stuck on it for about a week so far so I have started from scratch a few times. Here is what I have so far.
import java.util.*;
import java.io.*;
public class Patient
{
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
Scanner scan = new Scanner(args[0]);
String[] Rec = new String[10];
while(scan.hasNextLine)
{
scan.nextLine = Rec[i];
}
Arrays.sort(Rec);
for(int j=0; j<Rec.length; j++)
{
System.out.println(Rec[j]);
}
}
}
The number of lines is unknown
This would suggest you need a dynamic data structure which can grow to meet your needs. Consider using some kind of List
List<String> lines = new ArrayList<>(10);
while(scan.hasNextLine)
{
lines.add(scan.nextLine());
}
Have a look at Collections Trail for more details
Because you're dealing with structured data, I'd consider creating POJO of some kind to make it easier to manage...
public class PatientRecord {
private final String firstName;
private final String lastName;
private final int roomNumber;
private final int age;
public PatientRecord(String firstName, String lastName, int roomNumber, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.roomNumber = roomNumber;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getRoomNumber() {
return roomNumber;
}
public int getAge() {
return age;
}
}
Then, when you read the line from the file, you would parse it, creating a new instance of PatientRecord and add this to your List instead.
This means that you can then use things like Collections.sort to sort the List based on your needs
Now, I'm not too sure that this is exactly what you want, because they code you gave me isn't much, but here is your same code, fixed, slightly refactored, and set to return the lines as they are read in, but sorted by last name:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Patient {
public static void main(String args[]) {
System.out.println("Servando Hernandez");
System.out.println("Patient sorting Program.");
Scanner scan = null;
try {
scan = new Scanner(new File(args[0]));
} catch (FileNotFoundException e) {
System.err.println("File path \"" + args[0] + "\" not found.");
System.exit(0);
}
ArrayList<String> lines=new ArrayList<String>();
while(scan.hasNextLine())
lines.add(scan.nextLine());
Collections.sort(lines);
for(String x : lines)
System.out.println(x);
}
}
I hope this helps, and best of luck to you.

Method to check a Object's variables within an ArrayList

I'm having issues creating the following two methods using an ArrayList object:
existTextbook(): checks whether a given textbook is in the catalogue. existTextbook() accepts the title and the author and returns true or false. True if the textbook is in the catalogue, false otherwise.
deleteTexbook(): deletes a textbook from the catalogue. deleteTextbook() accepts a textbook title as parameter and deletes the textbook if it exists.
Searching the Java API, the closest method I can find for the first method is the contains method but it takes an object as a parameter, not a String object within the Textbook object like the title or author. The same is true for the remove method for the second method taking an object of the ArrayList as a parameter.
Any hints on how to have a method look at each Textbook object String title or author, then return true if a match is found, or to delete the Textbook object containing the Textbook object String title or author?
Here's my code so far:
Textbook Class
package Ex1;
import java.text.NumberFormat;
public class Textbook
{
private String category, title, author;
private int year;
private double price;
public Textbook (String category, String title, String author, int year,
double price)
{
this.category = category;
this.title = title;
this.author = author;
this.year = year;
this.price = price;
}
public String toString()
{
NumberFormat fmt = NumberFormat.getCurrencyInstance();
String description;
description = "Category: " + category + "\n";
description += "Title: " + title + "\n";
description += "Author: " + author + "\n";
description += "Year: " + year + "\n";
description += "Price: " + fmt.format(price) + "\n" + "\n";
return description;
}
}
Catalogue Class
package Ex1;
import java.util.ArrayList;
public class Catalogue
{
private ArrayList <Textbook> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Textbook>();
}
public void addTextbook (Textbook t)
{
catalogue.add(t);
}
public boolean existTextbook(String title, String author)
{
}
public void deleteTextbook(String title)
{
}
public String toString()
{
return catalogue.toString();
}
}
Driver Class
package Ex1;
public class Drivermain
{
public static void main(String[] args)
{
Textbook javaBook = new Textbook ("Computer Science",
"Java Software Solutions", "Lewis/Loftus", 2015, 163.45);
Textbook dataBook = new Textbook ("Computer Science",
"Data Structures and Algorithm Analysis in Java,",
"Mark A. Weiss", 2015, 181.90);
Textbook calcBook = new Textbook ("Mathematics",
"Calculus Plus NEW MyMathLab", "Briggs/Cochran/Gillett",
2015, 236.90);
Textbook osBook = new Textbook ("Computer Science",
"Operating Systems: Internals and Design Principles",
"William Stallings", 2015, 205.70);
Textbook historyBook = new Textbook ("History",
"History of the Canadian Peoples: Beginnings to 1867, Vol. 1",
"Conard/Finkel/Fyson", 2015, 96.90);
Catalogue bookCatalogue = new Catalogue();
bookCatalogue.addTextbook(javaBook);
bookCatalogue.addTextbook(dataBook);
bookCatalogue.addTextbook(calcBook);
bookCatalogue.addTextbook(osBook);
bookCatalogue.addTextbook(historyBook);
System.out.println(bookCatalogue);
bookCatalogue.existTextbook("Java Software Solutions", "Lewis/Loftus");
bookCatalogue.deleteTextbook("Java Software Solutions");
}
}
I think instead of using methods from collections, you may want to deal with looking in your Arraylist yourself.
I'm not using a for each loop (just a for loop) because for delete it will cause a concurrent modification exception.
package Ex1;
import java.util.ArrayList;
public class Catalogue
{
private ArrayList <Textbook> catalogue;
public Catalogue ()
{
catalogue = new ArrayList<Textbook>();
}
public void addTextbook (Textbook t)
{
catalogue.add(t);
}
public boolean existTextbook(String title, String author)
{
for(int i =0; i<catalogue.Size(); i++){
Textbook t = catalogue.get(i);
//you'll want getter and setter methods
if(t.author.equals(author)&&t.title.equals(title))
return truel
}
}
public void deleteTextbook(String title)
{
for(int i =0; i<catalogue.Size(); i++){
Textbook t = catalogue.get(i);
if(t.title.equals(title)){
catalogue.remove(i);
}
}
}
public String toString()
{
return catalogue.toString();
}
}
Happy Coding! Leave a comment if you have any questions.
Instead of directly using those methods you may consider just looping through the catalogue ArrayList yourself and testing if the current object matches the title (and author).
It might be overkill, but you could make Textbook implement Comparable or write a Comparator.

Categories