I'm working on a type of inventory program that deals with reading in a list of items from a file and I'm having some trouble.
Here's the code I have finished so far:
import java.util.Scanner;
import java.io.*;
public class Store {
public static void main(String[] args) throws Exception {
Book[] books = readInventory();
for (Book book : books) {
System.out.printf("ISBN: %s, Price: %f, Copies: %d%n",
book.getISBN(), book.getPrice(), book.getCopies());
}
}
public static Book[] readInventory() throws Exception {
Book[] books = new Book[15];
java.io.File file = new java.io.File("../instr/prog4.dat");
Scanner fin = new Scanner(file);
String isbn;
double price;
int copies;
int i = 0;
while (fin.hasNext()) {
isbn = fin.next();
if (fin.hasNextDouble()); {
price = fin.nextDouble();
}
if (fin.hasNextInt()); {
copies = fin.nextInt();
}
Book book = new Book(isbn, price, copies);
books[i] = book;
i++;
}
fin.close();
return books;
}
public static void printInfo(Book[] books) {
for(int x=0; x<books.length; x++) {
System.out.println("ISBN: " + books[x].getISBN() + "\n Price: " +
books[x].getPrice() + "\n Copies: " + books[x].getCopies());
}
}
}
class Book {
private String isbn;
private double price;
private int copies;
public Book(String isbnNum, double priceOfBook, int copiesInStock) {
isbn = isbnNum;
price = priceOfBook;
copies = copiesInStock;
}
public String getISBN() {
return isbn;
}
public double getPrice() {
return price;
}
public int getCopies() {
return copies;
}
public void setISBN(String isbn) {
this.isbn = isbn;
}
public void setPrice(double price) {
this.price = price;
}
public void setCopies(int copies) {
this.copies = copies;
}
#Override
public String toString() {
return String.format("ISBN: %s, Price: %f, Copies: %d%n",
this.getISBN(), this.getPrice(), this.getCopies());
}
}
The program compiles fine, but when I run the program I get the error
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Store.readInventory(Store.java:31)
at Store.main(Store.java:13)
Here is the contents of the file I am supposed to use:
1234567 31.67 0
1234444 98.50 4
1235555 27.89 2
1235566 102.39 6
1240000 75.65 4
1247761 19.95 12
1248898 155.91 0
1356114 6.95 17
1698304 45.95 3
281982X 31.90 5
I have been looking at another program I wrote recently that dealt with reading files to see that I was throwing the exceptions in the same types of places and it appears that I am (everything dealing with the file in that program was in the main method so that was the only one throwing an exception). From what I remember from an earlier Java programming class, we were supposed to throw exceptions at the main method and any other methods that deal with the file, so in this case I have the one on main and another on my readInventory() method.
What am I missing?
Check for next value before reading to avoid such exception as you are doing for isbn but not for price and copies.
sample code:
if(fin.hasNextDouble()){
price = fin.nextDouble();
}
if(fin.hashNextInt()){
copies = fin.nextInt();
}
For example Scanner#nextInt() method throws:
InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed
You are creating array of size 15 where is there is only 10 line in file that result in NullPointerException. Use List in that case.
You can use Java 7 - The try-with-resources Statement for better resource management even in case of error.
sample code
public static BookDetail[] readInventory() throws Exception {
List<BookDetail> books = new ArrayList<BookDetail>();
java.io.File file = new java.io.File("../instr/prog4.dat");
try (Scanner fin = new Scanner(file)) {
String isbn;
double price = 0;
int copies = 0;
while (fin.hasNext()) {
isbn = fin.next();
if (fin.hasNextDouble()) {
price = fin.nextDouble();
}
if (fin.hasNextInt()) {
copies = fin.nextInt();
}
BookDetail book = new BookDetail(isbn, price, copies);
books.add(book);
}
}
return books.toArray(new BookDetail[books.size()]);
}
Currently, you are checking if the file has more data, then you attempt to read 15 books, no matter what. Your for-loop goes from 0 to books.length-1, whatever is in the file.
Since you don't know (in theory) how many books there are in the file, you need to check fin.hasNext before reading each book.
So get rid of your for-loop and replace your reading code with something like this:
int i = 0;
while (fin.hasNext()) {
// read book here and assign to books[i]
// increment i for next iteration
i++;
}
The while condition fin.hasNext() will be checked before reading each book. When it returns false, you'll stop looping, and i will be the number of books you read.
Note that you're still assuming that each book has all its fields. If there was only half a book in the file, your code would still crash. But that's probably a good thing, since there's not really a way you can recover from that, and presumably you can assume you will receive only well-formed input.
I would suggest you use exception handling. I especially recommend using try with resources, since you forget to close the scanner that you are using.
You need to check in the code that you receive all the information that you need for each book. You don't want to have only partial information on the book just because you couldn't receive the rest of the data on that particular book.
Related
I recently saw a topic of some Uni coursework which was being conducted by a friend whom was instructed to do it a certain way. I thought I'd take the opportunity to jump in on the task.
I created a Book class like so:
class Book
{
private String author, title;
public Book setAuthor(String a)
{
author = a;
return this;
}
public Book setTitle(String t)
{
title = t;
return this;
}
public String getAuthor()
{
return author;
}
public String getTitle()
{
return title;
}
}
The concept is that a user can create multiple books at the start of the program and then search for an author:
private final static int BOOK_NO = 3;
private final static SO instance = new SO(); // This is whatever you called the class
public static void main(String[] args)
{
Book[] books = new Book[BOOK_NO];
Scanner kybd = new Scanner(System.in);
for(int i = 0; i < BOOK_NO; i++)
{
books[i] = instance.addBook(kybd, new Book());
}
Arrays.stream(instance.findBook(kybd, books)).forEach(o -> {
System.out.println(o.getTitle() + " by " + o.getAuthor());
});
}
public Book addBook(Scanner s, Book b)
{
System.out.println("Enter the Author of this book:");
b.setAuthor(s.next());
System.out.println("Enter the Title of this book:");
b.setTitle(s.next());
return b;
}
public Book[] findBook(Scanner s, Book[] bs)
{
System.out.println("Search a book by author:");
List<Book> finding = Arrays .stream(bs)
.filter(o -> o.getAuthor().equalsIgnoreCase(s.next()))
.collect(Collectors.toList());
System.out.println("Found " + finding.size() + " matches.");
Book[] output = new Book[finding.size()];
output = finding.toArray(output);
return output;
}
Now the whole program works fine, however I am experience unexpected behaviour with the Scanner when it comes to searching for a book. Here is a direct input/output behaviour I am experiencing:
Enter the Author of this book:
Foo
Enter the Title of this book:
Bar
Enter the Author of this book:
Foo
Enter the Title of this book:
FooBar
Enter the Author of this book:
Bar
Enter the Title of this book:
Foo
Search a book by author:
Foo
Foo
Foo
Found 2 matches.
Bar by Foo
FooBar by Foo
As you can see, I am having to type the author of the book into the scanner 3 times before getting any result. How can I mitigate this? What is causing this to happen?
This is because in your Stream you call next(), so for every Book object in the Stream, the Predicate in the call to filter is applied to it, and next() will be called. Resolve it to a variable so it isn't called more than once:
String book = s.next();
List<Book> finding = Arrays.stream(bs)
.filter(o -> o.getAuthor().equalsIgnoreCase(book))
.collect(Collectors.toList());
filter() accepts a Predicate, which in this case will be something like:
Predicate<String> pred = str -> str.equalsIgnoreCase(s.next());
So every time it is applied, next() will be called
What I have below is producing the desired results by print some employee details along with weekly / monthly wages as appropriate.
However I understand that I should not be inputting data in the constructor as I've done.
I need to prompt for a hours worked value only for "PartTimeEmployees", just not the way I've done it.
I've tested with For-Each loops, Enhanced For loops and using the instanceOf operator.
If I could get some guidance/hints or examples of how to accomplish what is currently being done in the constructor, but in the TestEmployee class instead that would be great.
Mostly I'm not sure how to even describe what I'm trying to achieve. This hinders Googling somewhat. (Help with a better title would also be great)
Thanks in advance.
public class TestEmployee
{
public static void main(String[] args)
{
int size;
Employee[] employees = new Employee[4];
employees[0] = new FullTimeEmployee("Jane", 26000);
employees[1] = new PartTimeEmployee("Jack");
employees[2] = new FullTimeEmployee("Lucy", 52000);
employees[3] = new PartTimeEmployee("Lenny");
for(int i = 0; i < employees.length; i++)
{
employees[i].print();
}
}
}
Class: PartTimeEmployee - Constructor:
public PartTimeEmployee(String thisName)
{
super(thisName);
System.out.println("Please enter the number of hours worked by " + thisName + ": ");
numHours = keyboard.nextInt();
setHours(numHours);
}
If I get your question, below might fit with your need -
First of all create generic Employee class -
class Employee {
private String name;
private int workingHours;
private final boolean IS_PART_TIME_EMP;
public Employee(String name, int workingHours) {
this.name = name;
this.workingHours = workingHours;
this.IS_PART_TIME_EMP = false;
}
public Employee(String name) {
this.name = name;
this.IS_PART_TIME_EMP = true;
}
public String getName() {
return name;
}
public int getWorkingHours() {
return workingHours;
}
public void setWorkingHours(int workingHours) {
this.workingHours = workingHours;
}
public boolean isPartTimeEmployee() {
return IS_PART_TIME_EMP;
}
}
Now you can use it as per your requirement.
Employee[] employees = new Employee[4];
employees[0] = new Employee("Jane", 26000);
employees[1] = new Employee("Jack");
employees[2] = new Employee("Lucy", 52000);
employees[3] = new Employee("Lenny");
Scanner sc = new Scanner(System.in);
for (Employee employee : employees) {
if(employee.isPartTimeEmployee()) {
System.out.println("Please enter working hours by " + employee.getName() + ": ");
int numHours = sc.nextInt();
employee.setWorkingHours(numHours);
}
}
Constructor is not meant for user input.Its main intention is to initialize object of that class.
Instead of doing that in constructor,you can try something like this
employees[1] = new PartTimeEmployee("Jack");
System.out.println("Please enter the number of hours worked by " + employees[1].getName()+ ": ");
numHours = keyboard.nextInt();
employees[1].setHours(numHours);
You most likely will have some logical main loop in your program, like
while(!quit) {
// 1. ask if you want to add part time or full time employee
// 2. ask proper questions
// 3. call correct constructor
}
Writing such small pseudo code algorithm should be self explanatory and get you going.
Step one: presentation of options available for user and reading user input.
Step two: performing actions depending on user input from step 1
Step three: final call to proper constructor depending on results from steps 1 and 2
If I understood your question correctly (which I'm really not sure of) you want to prompt for the employee data in the main method.
In that case I'd use a loop and query the following things:
name of the employee
does the employee work full time? (y/n)
if yes: what is the wage? (assume hours = whatever a full time employee works a day)
if no: how many hours? (and probably the hourly wage as well)
Then use that information to construct an Employee object (I don't see any need for the subclasses here).
I am running into some issues with my Java program. We have to create a library, which contains the title(halo, lotr) , the format (xbox, dvd etc), the date loaned (if it is ever loaned), and the person it is loaned to (if it is ever loaned).
I am not complete with my code, however I am testing it out as I go along instead of just compiling the entire finished code after 5 hours of coding. I am running into a problem. Whenever I set a public string variable to a value, it saves in the method I declared it in, but it will display "null" when system.out.print'd in other methods.
heres my code. First class is Library.
package p1;
import java.util.Scanner;
public class Library {
// \/ FIELDS
private String[] mediaItemTitle = new String[100];
public String[] mediaItemFormat = new String[100];
public String[] mediaItemLoanedTo = new String[100];
public String[] mediaItemOnLoan = new String[100];
public String[] mediaItemDateLoaned = new String[100];
public String today = "3/9/2015";
public int numberOfItems;
// /\ FIELDS
// \/ METHODS
public static void main(String[] brad){
Scanner input = new Scanner(System.in);
MediaItem main;
main = new MediaItem();
String title;
String format;
String date;
String name;
for ( int i = 0; i != 5; ){
i = displayMenu();
if (i == 1){
System.out.println("What is the title? ");
title = input.nextLine();
System.out.println("What is the format? ");
format = input.nextLine();
main.MediaItem(title,format);
}else if (i == 2){
System.out.println("Which Item (Enter the title? ");
title = input.nextLine();
System.out.println("Who are you loaning it to? ");
name = input.nextLine();
System.out.println("When did you loan it to them? ");
date = input.nextLine();
}else if (i == 3){
main.MediaItem();
}else if (i == 4){
System.out.print("Which item? (enter the title) ");
title = input.nextLine();
main.markReturned(title);
}else if (i == 5){ // DONE
System.out.print("Goodbye!");
break;
}
}
}
public static int displayMenu(){ // DONE
Scanner input = new Scanner(System.in);
int choice = 0;
System.out.println("1. Add new item");
System.out.println("2. Mark an item as on loan");
System.out.println("3. List all items");
System.out.println("4. Mark an item as returned");
System.out.println("5. Quit");
choice = input.nextInt();
return choice;
}
public void addNewItem(String title, String format){
this.mediaItemTitle[numberOfItems] = title;
this.mediaItemFormat[numberOfItems] = format;
System.out.print("TEST: " + mediaItemTitle[numberOfItems]);
}
public void incrementNumberOfItems(){
numberOfItems++;
}
public void listAllItems(){
for (int i = 0; i < numberOfItems; i++){
System.out.print(mediaItemTitle[i])
}
}
Here is the second part of code, my second class MediaItem
package p1;
public class MediaItem {
// \/ METHODS
public void MediaItem(){
Library list;
list = new Library();
list.listAllItems();
}
public void MediaItem(String title, String format){
Library call;
call = new Library();
call.addNewItem(title, format);
call.incrementNumberOfItems();
}
// /\ METHODS
}
This is driving me insane. I would love to just have me public variables save their value between methods but its not happening. the console (when 3 is chosen from displayMenu)
0
null
which means numberOfItems and mediaItemTitle[i] are read to be 0, and null. Which I dont understand, because I declared them earlier in the program!!!
I dont understand what Im doing wrong. please help me! Thank you!!
Your main mistake is that you are creating a new instance of Library inside your MediaItem method. That Library object will only live in the scope of MediaItem method. Plus Library is your main static class.
Your design is all wrong in my opinion. It looks like you are learning you way to Java or OOP, which is perfectly fine to have these mistakes.
Separate your data from your main class, create new classes just for your data. Have a look at java POJO (Plain Old Java Objects), like here
For example:
String title;
String format;
String date;
String name;
Should be in a new object, a POJO. Something like:
public class MyDataPOJO {
private String title;
private String format;
private String date;
private String name;
public MyDataPOJO(String title, String format, String date, String name) {
this.title = title;
this.format = format;
this.date = date;
this.name = name;
}
public String getTitle() {return title;}
public String getFormat() {return formate;}
// And the rest of the getter methods for date and name
}
In you Library class you may only need to hold your logic. But even that can be re-factored to another class.
On a side note, please check the java naming convention. Here is a guideline: link. In other words, start you methods name with lower case.
Example, your public void MediaItem(){/** something*/} should be public void mediaItem(){/** something*/ }
Follow the answer above and treat this as a comment, since the persons answer is correct and my statement isn't regarding your primary problem.
In your for-loop, I think you should add another else if statement. If the user enters a number that is not 1-5, they should receive an error. So maybe something like
else if (i < 1 || i > 5)
System.out.println("Error: Enter a choice 1-5\n");
Also, I think you may have forgotten a } to end your listAllItems() method.
But as I was saying, the answer to your real problem has already been handled, so give them the check mark. This is just a minor UI error I noticed.
I'm having problems changing the ISBN number to the name of the title of the book
Starts of printing the ISBN, author, title and level of book left:
0201403765 Jan Skansholm Ada 95 from the Beginning 100
0202535665 M. Ben-Ari Software Engineering 25
034565976X Michael Feldman Program Construction 12
080539057X M.A. Weiss Data Structures 30
0805645782 Ken Arnold Java for Programmers 10
0905297568 A. Badone Chaos Theory 15
Prints out whats in transactions.txt:
0201403765 -55
0201403765 2
0202535665 10
0202535665 -28
034565976X -7
080539057X -15
0905297568 13
0905297568 -5
So basically what I need to do is change the ISBN to the the title of the book if it matches, like this:
Java from the Beginning -55
Java from the Beginning 2
Software Engineering 10
Software Engineering -28
Program Construction -7
Data Structures -15
Chaos Theory 13
Chaos Theory -5
The problem im having is at 1 marked in the code below , really unsure how to check if the isbn matches and if so how to check what title matches the isbn and write it out , I think my problem is the arraylist ( should i make a third arraylist) or just make everything into arrays, any advice will do , cheers !!!! btw 1 is completely ludacrisly wrong....
import java.util.*;
import java.io.*;
class inventory{
static void intial(){
try{
RandomAccessFile in = new RandomAccessFile("books.dat","r");
ArrayList<String> list1=new ArrayList<String>();
String author ,title , isbn;
int level=0;
while(in.getFilePointer()<in.length()){
author = in.readUTF(); // author, at most 20 characters
title = in.readUTF(); // title, at most 40 characters
isbn = in.readUTF(); // ISBN
level = in.readInt(); // level, i.e. copies in stock (>=0)
//System.out.printf("%5d", isbn+author+title+level);
System.out.println(isbn+" "+author+" "+title+" "+level);
list1.add(title);
list1.add(isbn);
//list1.add(level);
}
in.close();
System.out.println(" ");
String isbn2;
int level2=0;
//try{
Scanner out = new Scanner(new File ("transactions.txt"));
ArrayList<String> list2=new ArrayList<String>();
while(out.hasNextLine()){
isbn2 = out.next();
level2 = out.nextInt();
System.out.println(isbn2 +" "+level2);
list2.add(isbn2);
//list2.add(level2);
}
out.close();
1) for (isbn: list1){
for(isbn2: list2){
if(isbn.contains(isbn2)){
System.out.println(title+" "+level);
}
}
}
}
catch(IOException f){
System.out.println("file error");
f.printStackTrace();
}
}
}
class BookShop{
public static void main(String[]args){
inventory x = new inventory();
x.intial();
First create a Book object to store your book data.
public Book{
private String ISBN ="";
private String title="";
private String author="";
private int level;
public Book(String ISBN, String title,String author, int level){
this.ISBN=ISBN;
this.title=title;
this.author=author;
this.level=level;
}
public String getTitle(){
return title;
}
public String getISBN(){
return ISBN;
}
public String getAuthor(){
return author;
}
public int getLevel(){
return level;
}
}
Add the Book objects to the ArrayList.
ArrayList<Book> bkList = new ArrayList<Book>();
bkList.add(new Book('ISBN','Title','Author'));
Get Book data with the get() method.
Book tempBook;
for (int x=0;x<bkList.Size();x++){
tempBook=bkList.get(x);
System.out.println(tempBook.getTitle()+" "+tempBook.getLevel());
}
I would create an object to hold each book, like this:
class Book {
public final String isbn;
public final String title;
public final String author;
public final int level;
public Book(String isbn, String title, String author, int level) {
this.isbn = isbn; this.title = title; this.author = author; this.level = level;
}
}
and populate the ArrayList with Book objects. That way everything for one Book is in one place, as opposed to needing parallel arrays.
(The way I wrote this class it is immutable, because you don't have any reason to update the objects once they're read in from the input file. If this was Python or Haskell we'd just use a tuple and do without the ceremony, but with Java we don't have that option.)
I have to read a text file line by line, except after 7 lines I want to use what's read by assigning the 7 lines to 7 different variables. Once I've assigned them, I want to use the variables. That is the easy part, which I know how to do, what has me stuck is that after I have used the 7 variables, I want to be able to assign the next 7 lines of my text file to the same variables, and use them again. I know I have to use loop(s), but ,
how do I make it stop after 7 lines instead of just re-assigning the lines to the variables?
Should I use 2 loops?
Or is there something similar to a break or maybe some sort of "pause" I can apply?
Or is there a some sort of counter that can be used with the FileReader class?
Or should I create one?
Here is what our teacher wants.
Parking Tickets
What to Do:
This assignment is based on Programming Challenge problem-8 on page 574 with some revisions so read this handout carefully. You are allowed to work in teams of 2 people if you desire. The collaboration and discussion would be helpful. Note: This is the longest and likely the most difficult program of the course so work carefully and follow the instructions.
For this assignment you will design a set of classes that work together to simulate a parking officer issuing parking tickets to some cars parked at meters. The problem may be a little artificial when compared to how real meters and tickets work.
You will design four separate classes and a demo program to run everything. Read this whole assignment to the end before starting to write Java code. You need to understand the structure of several classes and understand how the data file is organized.
The basic setting is a group of parking meters with cars parked at them for different amounts of time.
Each car will have purchased some parking time recorded in minutes. And each car will have parked for a certain length of time also recorded in minutes. Some will have parked for more time than they purchased and some for less time than purchased.
Here are the four classes you are required to develop.
• The ParkedCar Class: This class should simulate a parked car. The class’s responsibilities are as follows:
- To know the car’s make, model, color, license number
- To know the identity number of its parking meter.
- Has a toString() method to report its identifying information
• The ParkingMeter Class: This class will simulate a parking meter. The class’s responsibility is as follows:
- to know its own meter identity number
- To know the number of minutes that have been purchased
- To know the number of minutes parked
- has a toString() method to report its information
• The ParkingOfficer Class: This class should simulate a parking officer inspecting parked cars. The class’s responsibilities are as follows:
- Has two instance variables: one for name and one for badge number of the officer
- Has a constructor with two parameters for the parking officer’s name and badge number
- Has a toString() method
- Has an examine() method which receives a ParkedCar object, and a ParkingMeter object as parameters. This method determines whether the time has expired or not
If time has expired it creates a parking ticket object which is returned as the return value from examine().
If time has not expired it returns null.
• The ParkingTicket Class: This class will simulate a parking ticket. The class’s responsibility is as follows:
- Has a constructor which receives as parameters a ParkedCar object, a ParkingMeter object and a ParkingOfficer object which are used to initialize corresponding instance variables in the class. Be sure to use copy constructors for each of these parameter objects.
- This class also has an instance variable for the amount of fine.
- The fine is calculated by the ParkingTicket constructor:
The fine is $25 for the first hour or part of an hour that the car is illegally parked, plus $10 for every additional hour or part of an hour that the car is illegally parked.
If time has not expired the fine is set to zero.
- Has a toString() method which prepares the ticket in a useful format of your design (try to match the sample output shown below or make your own improvements. It must report the make, model, color, and license number of an illegally parked car. It also reports the amount of the fine and the name and badge number of the police officer issuing the ticket. In this toString() method you must make effective use of the toString() methods for the other classes in parking ticket (i.e. the ParkedCar, the ParkingMeter, and the ParkingOfficer)
Testing Class
Write a testing class, TicketDemo, with main() to run the simulation using the above classes as follows:
• Create a PoliceOfficer object. Make up your own name and badge number. You may hard-wire this into your test program or ask the user for input data (your choice).
• In a loop read data from the data file Asg-5_in.txt. (Note: the file Asg-5_inExplain.txt describes how to interpret the file content.)
o Read one block of data for a car and a meter and create a ParkedCar object and a ParkingMeter object
o Call the parking officer examine() method using your ParkedCar and Parking meter objects as arguments. The examine method will return a ticket or null.
o If a ticket is returned, call the toString() method to print the ticket on the screen.
o If no ticket is issued print identification information about the car (use its toString() method.
o Let the loop repeat until there is no more data available from the input file.
Here is what I have so far, although I'm nowhere near being done.
ParkedCar class:
public class ParkedCar{
private String make;
private String model;
private String color;
private String license;
private String meterID;
public String getMake(String make)
{
this.make = make;
return make;
}
public String getModel(String model)
{
this.model = model;
return model;
}
public String getColor(String color)
{
this.color = color;
return color;
}
public String getLicense(String license)
{
this.license = license;
return license;
}
public String getMeterID(String meterID)
{
this.meterID = meterID;
return meterID;
}
public String toString()
{
String str = "\nMake: " + make + "\nModel: " + model + "\nColor: " + color +
"\nLicense: " + license + "\nMeter ID: " + meterID;
return str;
}
}
ParkingMeter class:
public class ParkingMeter{
private String meterID;
private int minsPurchased;
private int minsParked;
public String getMeterID(String meterID)
{
this.meterID = meterID;
return meterID;
}
public int getMinsPurchased(int minsPurchased)
{
this.minsPurchased = minsPurchased;
return minsPurchased;
}
public int getColor(int minsParked)
{
this.minsParked = minsParked;
return minsParked;
}
public String toString()
{
String str = "\nMeter ID: " + meterID + "\nMinutes Purchased: " + minsPurchased +
"\nMinutes Parked: " + minsParked;
return str;
}
}
ParkingOfficer class:
public class ParkingOfficer{
private String officerName;
private String badgeNumber;
public ParkingOfficer(String officerName, String badgeNumber)
{
this.officerName = officerName;
this.badgeNumber = badgeNumber;
}
public ParkingOfficer(ParkingOfficer object2)
{
officerName = object2.officerName;
badgeNumber = object2.badgeNumber;
}
public void setParkingOfficer(String officerName, String badgeNumber)
{
this.officerName = officerName;
this.badgeNumber = badgeNumber;
}
public String toString()
{
String str = "\nOfficer's Name: " + officerName + "\nOfficer's Badge Number: " + badgeNumber;
return str;
}
}
int lineCounter = 0;
int variableCounter = 7;
BufferedReader br = new BufferedReader(new FileReader(new File("your-file-here.txt")));
String line = "";
List<String> lineSavers = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lineSavers.add(line);
++lineCounter;
if (lineCounter == variableCounter) {
// do something with the lineSaver
lineSavers.clear();
linteCounter = 0;
// start the cycle again.
}
}
There's a lot of stuff that I didn't consider here:
Cleaning up resources - I didn't close the reader.
What happens if you read a file whose line count isn't evenly divided by 7. You'll never get those last lines the way I wrote it.
Hard coded variable counter. I'd make that a variable to be passed in.
Not very modular; I'd pass in that file name and encapsulate the whole thing in a method.
I'd try a more functional approach where I'd pass back what I wanted and then operate on it rather than mingle reading and processing together.
Why seven lines? What are you doing with them? Are they really related in a way that'd be better expressed as an object? You're probably not thinking about the problem in the best way.
You could use commons-io to read the file in one go, and then loop over the list. A bit of example code:
public static void main(String[] args) {
// Read the content of the file in one go
InputStream input = null;
// This is where the file content is stored
List<String> lines = null;
try {
input = new FileInputStream("input.txt");
lines = IOUtils.readLines(new BufferedInputStream(input));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// Always (try to) close the file
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (lines != null) {
String[] params = null; // per 7 lines
for (int i = 0; i < lines.size(); i++) {
int fromZeroToSixCounter = i % 7;
if ( fromZeroToSixCounter == 0 ) {
if (params != null) {
// the first time (i == 0) params is null and this will not execute
doSomethingWithParams(params);
}
// new batch of 7 lines
params = new String[7];
}
params[fromZeroToSixCounter] = lines.get(i);
}
if (params != null) {
// the last batch
doSomethingWithParams(params);
}
}
}
public static void doSomethingWithParams(String[] params) {
System.out.println("New batch");
for (int i=0; i < params.length; i++) {
System.out.println(params[i]);
}
}
A basic structure would be something like this:
while (true) {
String v1 = reader.readLine();
if (v1 == null)
break;
String v2 = reader.readLine();
...
String v7 = reader.readLine();
/* Do what ever you want with v1 through v7. */
...
}
/* End of loop. */