java.lang.RuntimeException: Cannot open files - java

I have DataManager.java and ExportBasicTest.java for tests.
I can't get my DataManager.java to pass the tests, even though they seem like basic errors.
I tried messing around with the directories of the two files and the file that I create called ExportedFile.txt but I can't fix any of my errors.
I have two arrayLists of type <Passenger> and <Flight> which have different parts of each. These parts are what my long methods are referencing.
DataManager.java:
import java.io.*;
import java.util.*;
public class DataManager {
private static File fileName;
private static Formatter fileFormatter;
private static ArrayList<Flight> theFlights;
private static ArrayList<Passenger> thePassengers;
public static void exportData(String filename, ArrayList<Passenger> passengers, ArrayList<Flight> flights) {
fileName = new File(filename);
theFlights = flights;
thePassengers = passengers;
openFile();
addFlights();
addPassengers();
closeFile();
}
public static void openFile(){
try{
fileFormatter = new Formatter(fileName);
System.out.println("you created a file");
}
catch(Exception e){
System.out.println("You have an error.");
}
}
public static int AlertsCount(int i){
return thePassengers.get(i).getAlerts().size();
}//AlertsCount
public static String listAlerts(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getAlerts().size();z++){
stringBuilder.append(thePassengers.get(i).getAlerts().get(z) + System.getProperty("line.separator"));
}
String alerts = stringBuilder.toString();
return alerts;
}//listAlerts close
public static int BookedFlightsCount(int i){
return thePassengers.get(i).getBookedFlights().size();
}//bookedFlightsCount close
public static String listBookedFlights(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getBookedFlights().size();z++){
stringBuilder.append(thePassengers.get(i).getBookedFlights().get(z).getSourceAirport() + " , " +
thePassengers.get(i).getBookedFlights().get(z).getDestinationAirport() + " , " +
Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getTakeOffTime()) + " , " +
Integer.toString(thePassengers.get(i).getBookedFlights().get(z).getLandingTime()) + System.getProperty("line.separator"));
}
String bookedFlights = stringBuilder.toString();
return bookedFlights;
}//listBookedFlights close
public static int StandbyFlightsCount(int i){
return thePassengers.get(i).getStandbyFlights().size();
}//StandbyFlightsCount close
public static String listStandbyFlights(int i){
StringBuilder stringBuilder = new StringBuilder();
for(int z = 0;z<thePassengers.get(i).getStandbyFlights().size();z++){
stringBuilder.append(System.getProperty("line.separator") + thePassengers.get(i).getStandbyFlights().get(z).getSourceAirport() + " , " +
thePassengers.get(i).getStandbyFlights().get(z).getDestinationAirport() + " , " +
Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getTakeOffTime()) + " , " +
Integer.toString(thePassengers.get(i).getStandbyFlights().get(z).getLandingTime()));
}
String standbyFlights = stringBuilder.toString();
return standbyFlights;
}//listStandbyFlights close
public static void addPassengers(){
fileFormatter.format("%s%d", "#passCount ", thePassengers.size());
for(int i = 0; i<thePassengers.size();i++){
fileFormatter.format("%s%s%s%s%s%s%d%s%s%d%s%s%d%s",System.getProperty("line.separator"), "#newPass",System.getProperty("line.separator"), thePassengers.get(i).getFirstName()+" , ", thePassengers.get(i).getLastName(),System.getProperty("line.separator"),
AlertsCount(i),System.getProperty("line.separator"), listAlerts(i), BookedFlightsCount(i),System.getProperty("line.separator"), listBookedFlights(i), StandbyFlightsCount(i), listStandbyFlights(i));
}
}//addPassengers close
public static void addFlights(){
fileFormatter.format("%s%d%s", "#flightCount ", theFlights.size(), System.getProperty("line.separator"));
for(int i = 0;i<theFlights.size();i++){
fileFormatter.format("%s%s%s , %s , %d , %d%s%d%s", "#newFlight",System.getProperty("line.separator"), theFlights.get(i).getSourceAirport(), theFlights.get(i).getDestinationAirport(),
theFlights.get(i).getTakeOffTime(), theFlights.get(i).getLandingTime(), System.getProperty("line.separator"),theFlights.get(i).getCapacity(),System.getProperty("line.separator"));
}
}//addFlights close
public static void closeFile(){
fileFormatter.close();
}//closeFile close
//This function creates and writes data for a new file using the specifications ,
//given earlier in order to store the data represented by those objects stored within the two ArrayLists.
}
ExportBasicTest.java:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import junit.framework.Assert;
import org.junit.Test;
public class ExportBasicTest {
#Test(timeout = 1000)
public void exportExampleFile()
{
ArrayList<Flight> flightList = new ArrayList<Flight>();
Flight f1 = new Flight("MCO", "MIA", 800, 930, 8);
Flight f2 = new Flight("MIA", "ATL", 1100, 1400, 23);
Flight f3 = new Flight("ATL", "GNV", 1430, 1615, 15);
flightList.add(f1);
flightList.add(f2);
flightList.add(f3);
ArrayList<Passenger> passList = new ArrayList<Passenger>();
Passenger p1 = new Passenger("Joshua", "Horton");
Passenger p2 = new Passenger("Adam", "Smith");
passList.add(p1);
passList.add(p2);
p1.addAlert("The 7:30 flight from BTR to GNV has been cancelled!");
p1.bookFlight(f1);
p1.bookFlight(f2);
p2.bookFlight(f3);
p2.addStandbyFlight(f1);
p2.addStandbyFlight(f2);
DataManager.exportData("ExportedFile.txt", passList, flightList);
// This file, given the initial setup, should almost perfectly match the provided example file.
Assert.assertEquals("File contents are not as expected!", true, matchFiles("ProjStage3BasicFile.txt", "ExportedFile.txt"));
}
// Checks if the files match by directly comparing their exact contents.
private boolean matchFiles(String expected, String actual)
{
Scanner inFile1;
Scanner inFile2;
try
{
inFile1 = new Scanner(new File(expected));
inFile2 = new Scanner(new File(actual));
}
catch(IOException e)
{
throw new RuntimeException("Cannot open files!", e);
}
ArrayList<String> expectedLines = new ArrayList<String>();
ArrayList<String> actualLines = new ArrayList<String>();
while(inFile1.hasNextLine())
{
expectedLines.add(inFile1.nextLine());
}
while(inFile2.hasNextLine())
{
actualLines.add(inFile2.nextLine());
}
// Erase a trailing blank line at the file's end; I don't mind that.
if(actualLines.get(actualLines.size() - 1).trim().equals(""))
{
actualLines.remove(actualLines.size() - 1);
}
return expectedLines.equals(actualLines);
}
}

You need to pass the path to the files not just the names where ever you use a filename.
Your match files method is throwing an error because it cannot open the file names you passed. To use the current working directory use ./ as in "./filename.txt" as opposed to "filename.txt"
You can always check if a path exists Using java.nio.file.Files
if(Files.exists(path)){...}

Related

find the list of unique words contained in 2 text files in java using arrays

I need to read two text files and display all the unique words in both the text files.(the words in both 2 files can only be printed once)
file1.txt
lion
tiger
cheetah
elephant
cow
file2.txt
mouse
dog
cow
cat
lion
expected output :
lion
tiger
cheetah
elephant
cow
dog
cat
mouse
public class Workshop {
static int count1 = 0;
static int count2 = 0;
private static final String FILE1 = "C:\\Users\\shagi\\Desktop\\file1.txt";
private static final String FILE2 = "C:\\Users\\shagi\\Desktop\\file2.txt";
static String arrayLines1[] = new String[countLines(FILE1)];
static String arrayLines2[] = new String[countLines(FILE2)];
static String totalArray[] = new String[arrayLines1.length + arrayLines2.length];
static String arrayLines1new[]=new String[countLines(FILE1)];
static int flag = 0;
static int k=arrayLines1.length;
public static void main(String[] args) throws IOException {
readFile(FILE1, FILE2);
displaySimilar();
displayAll();
}
public static int countLines(String File) {
int lineCount = 0;
try {
BufferedReader br = new BufferedReader(new FileReader(File));
while ((br.readLine()) != null) {
lineCount++;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return lineCount;
}
public static void readFile(String File1, String File2) {
String contents1 = null;
String contents2 = null;
try {
FileReader file1 = new FileReader(File1);
FileReader file2 = new FileReader(File2);
BufferedReader buf1 = new BufferedReader(file1);
BufferedReader buf2 = new BufferedReader(file2);
while ((contents1 = buf1.readLine()) != null) {
arrayLines1[count1] = contents1;
count1++;
}
while ((contents2 = buf2.readLine()) != null) {
arrayLines2[count2] = contents2;
count2++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
There are two methods which i tried to find the ans for my question
Method 1
public static void displayAll() {
for (int i =0; i<k-1;i++){
System.out.println(totalArray[i]);
}
System.out.println(totalArray[k-1]);
System.out.println("");
int p=0;
for (int i=0;i<arrayLines2.length;i++){
for (int j=0;j<arrayLines1.length;j++){
if (arrayLines2[i].equals(arrayLines1[j])){
flag=1;
break;
} else {
flag=0;
}
if (flag==1){
arrayLines1new[p]=arrayLines2[i];
p++;
}
}
}
Method 2
public static void displayAll() {
for (int i=0;i<arrayLines1.length;i++){
String a=arrayLines1[i];
for (int j=0;j<arrayLines2.length;j++){
String b =arrayLines2[j];
if (!a.equals(b)){
System.out.println(a);
}
}
}
}
But both doesnt give the expected output
There is lot of redundant code. Here is a simpler and shorter version.
I am using Set and its operations to find common (intersection), uncommon and all unique words.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class Workshop {
private static final String FILE1 = "C:\\Users\\shagi\\Desktop\\file1.txt";
private static final String FILE2 = "C:\\Users\\shagi\\Desktop\\file2.txt";
static Set<String> file1Words = new HashSet<String>();
static Set<String> file2Words = new HashSet<String>();
static Set<String> allWords = new HashSet<String>();
static Set<String> commonWords = new HashSet<String>();
static Set<String> uncommonWords = new HashSet<String>();
public static void main(String[] args) throws IOException {
file1Words.addAll(readFile(FILE1));
file2Words.addAll(readFile(FILE2));
System.out.println("file1 : " + file1Words);
System.out.println("file2 : " + file2Words);
displaySimilar();
System.out.println("common : " + commonWords);
displayAll();
System.out.println("all : " + allWords);
displayUnCommon();
System.out.println("uncommon : " + uncommonWords);
}
public static void displaySimilar() {
commonWords.addAll(file1Words);
commonWords.retainAll(file2Words);
}
public static void displayUnCommon() {
uncommonWords.addAll(file1Words);
uncommonWords.addAll(file2Words);
uncommonWords.removeAll(commonWords);
}
public static Set<String> readFile(String file) {
Set<String> words = new HashSet<String>();
try {
FileReader fileReader = new FileReader(file);
BufferedReader buffer = new BufferedReader(fileReader);
String content = null;
while ((content = buffer.readLine()) != null) {
words.add(content);
}
} catch (Exception e) {
e.printStackTrace();
}
return words;
}
public static void displayAll() {
allWords.addAll(file1Words);
allWords.addAll(file2Words);
}
}
Sample Run:
file1 : [lion, cheetah, tiger, elephant, cow]
file2 : [lion, mouse, cat, cow, dog]
common : [lion, cow]
all : [cheetah, lion, cat, mouse, tiger, elephant, cow, dog]
uncommon : [cheetah, cat, mouse, tiger, elephant, dog]
This would be a good situation for a HashMap. The keys would be the words and the values would be the number of occurrences. You could then print out the keys with a value of 1. The pseudo code would look like this:
Initialize the map: HashMap <String, Integer> wordMap = new HashMap<>();
For each file:
-- For each word:
---- Put the word in wordMap with the appropriate value.
For each key in wordMap:
-- If wordMap.get(key) == 1, print out the key
You could also accomplish the same thing using two arrayLists, using one to keep track out the words and another to keep track of the counts.
Both methods have an O(N) time complexity, but using the map is more performant because the maps's values can be updated in O(1).

Write and Read a Vector to a serialized file in Java?

I am trying a vector to a serialized file. The vector is made of a class I created. Below is the class.
public class Product implements java.io.Serializable{
public String description;
public String code;
public double price;
public String unit;
public Product(String w, String x, double y, String z){ //Constructor for Product
description = w;
code = x;
price = y;
unit = z;
}
}
I created a vector:
BufferedReader in =new BufferedReader(new InputStreamReader(System.in));
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.ser"));
Vector <Product> products=new Vector();//declare a vector of products
for(int i=0;i<101;i++){//enter the values for the class
System.out.print("Description: ");
String w = in.readLine();
char f = w.charAt(0);
if(f=='#'){//Statement to break out of the loop when the user enters #
System.out.println();
break;
}else{//Code to read input from user
System.out.print("Code: ");
String x = in.readLine().toUpperCase();
boolean finished=false;
while(!finished){
System.out.print("Price: ");
String a =in.readLine();
try{//try catch statement
double y= Double.parseDouble(a);
System.out.print("Unit: ");
String z = in.readLine();
Product temp = new Product(w, x, y, z);
products.insertElementAt(temp, i);//values are assigned to
//the vector elements
System.out.println();
finished=true;
}
catch(Exception e){
System.out.println("do not enter letters for the price");
}
}
}
}
So I have a vector of Product. What I need to know is how to write it to into a serialized file, file.ser, then how to read from that file back into a vector of Product. I have been experimenting with this for a whole day and can't seem to get anything right or find anything useful on the internet.
I added a toString() method do class Product to get proper debug output:
public class Product implements Serializable {
// ....
#Override
public String toString() {
return description + "/" + code + "/" + price + "/" + unit;
}
}
You can put the whole vector instance to the ObjectOutputStream.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
public class Main {
private static final String FILE_NAME = "file.ser";
public static void main(String[] args) throws Exception {
final Vector<Product> products = new Vector<Product>();
products.add(new Product("1", "1", 1.0, "1"));
products.add(new Product("2", "2", 2.0, "2"));
products.add(new Product("3", "3", 3.0, "3"));
products.add(new Product("4", "4", 4.0, "4"));
System.out.println("Original products : " + products);
final ObjectOutputStream out = new ObjectOutputStream(
new BufferedOutputStream(new FileOutputStream(FILE_NAME)));
try {
out.writeObject(products);
} finally {
out.close();
}
final ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(FILE_NAME)));
final Vector<Product> productsFromFile = (Vector<Product>) in.readObject();
System.out.println("Products from file: " + productsFromFile);
}
}
And the output is:
Original products : [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Products from file: [1/1/1.0/1, 2/2/2.0/2, 3/3/3.0/3, 4/4/4.0/4]
Try something like the following to write a serialisable object:
Product product = new Product("Apples", "APP", 1.99, 200);
try{
OutputStream file = new FileOutputStream( "output.ser" );
OutputStream buffer = new BufferedOutputStream( file );
ObjectOutput output = new ObjectOutputStream( buffer );
try{
output.writeObject(product);
}
finally{
output.close();
}
}
catch(IOException ex){
System.out.println("Output failed.");
}
To read it in you read do the opposite, putting result into an object as follows:
Product product = (Product)input.readObject();
where input is an ObjectInputStream.
I think that you can use this example to write and read the file:
http://www.java-samples.com/showtutorial.php?tutorialid=392
you can search in google for: "java file reader example"
regards
I think that you forgot to add the vector to the class. In your code you assign temp to new Product, then you add the values to the vector. Vector is filled with new values, but Vector is not part of the class Product. Therefore, the data is still in Vector, but it's will never be saved via serializable. (if this is what you try to accomplish)
Here is a small example (written in Java Processing):
import java.io.*;
GameChar Elf, Troll;
void setup() {
Elf = new GameChar(50, new String[] {
"bow", "sword", "dust"
}
);
Troll = new GameChar(200, new String[] {
"bare hands", "big axe"
}
);
try {
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(sketchPath+"/data/game.txt"));
os.writeObject(Elf);
os.writeObject(Troll);
os.close();
}
catch (Exception e) {
println(e);
}
Elf = null;
Troll = null;
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(sketchPath+"/data/game.txt"));
Elf = (GameChar) is.readObject();
Troll = (GameChar) is.readObject();
println("Elf has "+ Elf.getHealth()+" health, and fights with "+ Elf.getWeapons());
println("Troll has "+ Troll.getHealth()+" health, and fights with "+ Troll.getWeapons());
}
catch (Exception e) {
println(e);
}
}
void draw() {
}
static class GameChar implements Serializable {
int health;
String[] weapons;
GameChar(int h, String[] w) {
health = h;
weapons = w;
}
int getHealth() {
return health;
}
String getWeapons() {
String weaponList = "";
for (String weapon : weapons)
weaponList += weapon + " ";
return weaponList;
}
}

fill arrayList with dat file

Here's the code:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib
{
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public MadLib()
{
loadNouns();
loadVerbs();
loadAdjectives();
out.println(nouns);
}
public MadLib(String fileName)
{
//load stuff
loadNouns();
loadVerbs();
loadAdjectives();
try{
Scanner file = new Scanner(new File(fileName));
}
catch(Exception e)
{
out.println("Houston we have a problem!");
}
}
public void loadNouns()
{
nouns = new ArrayList<String>();
try{
//nouns = new ArrayList<String>();
String nou = "";
Scanner chopper = new Scanner(new File ("nouns.dat"));
//chopper.nextLine();
while(chopper.hasNext()){
nou = chopper.next();
out.println(nou);
nouns.add(nou);
//chopper.nextLine();
}
//chopper.close();
out.println(nouns.size());
}
catch(Exception e)
{
out.println("Will");
}
}
public void loadVerbs()
{
verbs = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("verbs.dat"));
while(chopper.hasNext()){
verbs.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
out.println("run");
}
}
public void loadAdjectives()
{
adjectives = new ArrayList<String>();
try{
Scanner chopper = new Scanner(new File("adjectives.dat"));
while(chopper.hasNext()){
adjectives.add(chopper.next());
chopper.nextLine();
}
chopper.close();
}
catch(Exception e)
{
}
}
public String getRandomVerb()
{
String verb = "";
int num = 0;
num = (int)(Math.random()*(verbs.size()-1));
verb = verbs.get(num);
return verb;
}
public String getRandomNoun()
{
String noun = "";
int num = 0;
if(nouns == null){
loadNouns();
}
double rand = (Math.random());
num = (int)(rand * (nouns.size()-1));
out.println(num);
noun = nouns.get((int) num);
out.print(noun);
return noun;
}
public String getRandomAdjective()
{
String adj = "";
int num = 0;
num = (int)(Math.random()*(adjectives.size()-1));
adj = adjectives.get(num);
return adj;
}
public String toString()
{
String output = "The " + getRandomNoun() + getRandomVerb() + " after the " + getRandomAdjective() + getRandomAdjective() + getRandomNoun() + " while the " + getRandomNoun() + getRandomVerb() + " the " + getRandomNoun();
return output;
}
}
and here's one of the .dat files (the other 2 are the exact same aside from the specific words they contain):
dog
pig
chicken
building
car
person
place
thing
truck
city
state
school
student
bird
turkey
lion
tiger
alligator
elephant
My issue is that I can't get any of my arrayLists to read in their appropriate .dat files and from my POV, my code seems like it should do that
UPDATE
current output aside from the absence of "Will" (I removed that line):
run
[ ]
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at MadLib.getRandomNoun(MadLib.java:130)
at MadLib.toString(MadLib.java:147)
at java.lang.String.valueOf(Unknown Source)
at java.io.PrintStream.println(Unknown Source)
at Lab16d.main(Lab16d.java:18)
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.*;
public class MadLib {
private ArrayList<String> verbs = new ArrayList<String>();
private ArrayList<String> nouns = new ArrayList<String>();
private ArrayList<String> adjectives = new ArrayList<String>();
public static void main(String args[]) {
MadLib a = new MadLib();
System.out.println(a.toString());
}
public MadLib() {
loadAllWords();
System.out.println(nouns);
}
public MadLib(String fileName) {
loadAllWords();
try {
Scanner file = new Scanner(new File(fileName));
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadAllWords() {
loadNouns();
loadVerbs();
loadAdjectives();
}
public void loadNouns() {
nouns = loadFile("nouns.dat");
}
public void loadVerbs() {
verbs = loadFile("verbs.dat");
}
public void loadAdjectives() {
adjectives = loadFile("adjectives.dat");
}
public ArrayList<String> loadFile(String filename) {
ArrayList<String> words = new ArrayList<String>();
try {
Scanner chopper = new Scanner(new File(filename));
while (chopper.hasNext()) {
words.add(chopper.next());
// just calling nextLine will cause an exception at the end of the file unless you have an blank line there on purpose, so this makes sure it does
if (chopper.hasNext()) {
chopper.nextLine();
}
}
chopper.close();
} catch (Exception e) {
e.printStackTrace();
}
return words;
}
public String getRandomWord(ArrayList<String> words) {
Random rand = new Random();
int num = rand.nextInt(words.size());
String word = nouns.get(num);
System.out.println(word);
return word;
}
public String getRandomVerb() {
if (verbs == null) {
loadNouns();
}
return getRandomWord(verbs);
}
public String getRandomNoun() {
if (nouns == null) {
loadNouns();
}
return getRandomWord(nouns);
}
public String getRandomAdjective() {
if (adjectives == null) {
loadNouns();
}
return getRandomWord(adjectives);
}
public String toString() {
return "The " + getRandomNoun() + " " + getRandomVerb() + " after the " + getRandomAdjective() + " " + getRandomAdjective() + " " + getRandomNoun() + " while the " + getRandomNoun() + " " + getRandomVerb() + " the " + getRandomNoun();
}
}

Trouble with a small library-management program

I'm having major trouble piecing this together. I have basic read and write functionality. What I need is for the input from file 'Books.txt' to be checked so that:
ISBN is valid
CopyNumber, Year and Statistics should be numeric
Title, Author and Publisher must contain values
BorrowDate must be a valid date
ReturnDate if available must be a valid date
LibraryCardNumber if available must be numeric.
If a book is not borrowed the two last fields are nonexistent.
2 sample rows from 'Books.txt':
9780140455168#2#The Twelve Caesars#Suetonius#Penguin Classics#2007#3#101009#101030#5478
9780141188607#1#Claudius the God#Robert Graves#Penguin Classics#2006#2#080123
Error lines should be written to 'ErrorLines.txt' with an error-message, e.g. Wrong ISBN. Error-free books should be written to 'NewBooks.txt' sorted by name of author.
Here's what I've got so far. I'm not looking for a complete solution, because I obviously have a looong way to go, but if someone would be so kind as to give me some pointers, I'd be extremely grateful! And yes, it's homework :D
Do I need to make a try loop to validate the input...?
The Library class:
import java.util.ArrayList;
import java.util.*;
import java.io.*;
import java.io.IOException;
public class Library {
public void readFromFile (String filename) throws IOException {
String inLine;
File inFile;
inFile = new File("Books.txt");
BufferedReader fIn = new BufferedReader(new FileReader(inFile));
inLine = fIn.readLine();
while (inLine != null) {
inLine = fIn.readLine();
aBookList.add(inLine + "\n");
}
fIn.close();
}
public void writeToFile (String fileName) throws IOException {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(fileName));
bw.write("???"); //Dont know what to put here...
bw.newLine();
} catch (IOException e) {
System.out.println("Error writing file.");
} finally {
bw.close();
}
}
public static boolean isISBN13Valid(isbn) {
int check = 0;
for (int i = 0; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1));
}
for (int i = 1; i < 12; i += 2) {
check += Integer.valueOf(isbn.substring(i, i + 1)) * 3;
}
check += Integer.valueOf(isbn.substring(12));
return check % 10 == 0;
}
}
And here's the Book class:
import java.util.*;
import java.io.*;
public class Book {
Book b = new Book();
private static ArrayList<String> aBookList = new ArrayList<String>();
private String Isbn;
private int CopyNumber;
private String Title;
private String Author;
private String Publisher;
private int Year;
private int Statistics;
private String BorrowDate;
private String ReturnDate;
private int LibraryCardNumber;
public void bookInfo (String nIsbn, int nCopyNumber, String nTitle, String nAuthor, String nPublisher, int nYear,
int nStatistics, String nBorrowDate, String nReturnDate, int nLibraryCardNumber) {
Isbn = nIsbn;
CopyNumber = nCopyNumber;
Title = nTitle;
Author = nAuthor;
Publisher = nPublisher;
Year = nYear;
Statistics = nStatistics;
BorrowDate = nBorrowDate;
ReturnDate = nReturnDate;
LibraryCardNumber = nLibraryCardNumber;
}
public void bookInfo (String Row) {
StringTokenizer sT = new StringTokenizer(Row);
Isbn = sT.nextToken("#");
CopyNumber = Integer.parseInt(sT.nextToken("#") );
Title = sT.nextToken("#");
Author = sT.nextToken("#");
Publisher = sT.nextToken("#");
Year = Integer.parseInt(sT.nextToken("#") );
Statistics = Integer.parseInt(sT.nextToken("#") );
BorrowDate = sT.nextToken("#");
ReturnDate = sT.nextToken("#");
LibraryCardNumber = Integer.parseInt(sT.nextToken("#") );
}
public void setIsbn(String nIsbn) {
Isbn = nIsbn;
}
public void setCopynumber(int nCopyNumber) {
CopyNumber = nCopyNumber;
}
public void setTitle(String nTitle) {
Title = nTitle;
}
public void setAuthor(String nAuthor) {
Author = nAuthor;
}
public void setPublisher(String nPublisher) {
Publisher = nPublisher;
}
public void setYear(int nYear) {
Year = nYear;
}
public void setStatistics(int nStatistics) {
Statistics = nStatistics;
}
public void setBorrowDate(String nBorrowDate) {
BorrowDate = nBorrowDate;
}
public void setReturnDate(String nReturnDate) {
ReturnDate = nReturnDate;
}
public void setLibraryCardNumber(int nLibraryCardNumber) {
LibraryCardNumber = nLibraryCardNumber;
}
public String getAll () {
String s = " ";
return (Isbn + s + CopyNumber + s + Title + s + Author + s + Publisher + s +
Year + s + Statistics + s + BorrowDate + s + ReturnDate + s +
LibraryCardNumber);
}
public void showAll () {
String t = "\t";
System.out.println(Isbn + t + CopyNumber + t + Title + t + Author + t +
Publisher + t + Year + t + Statistics + t +
BorrowDate + t + ReturnDate + t + LibraryCardNumber);
}
}
And finally there's the Main class with main method:
public class Main<aBookList> implements Comparable<aBookList> {
public static void main(String [] args) throws Exception {
new Library().readFromFile("Books.txt");
new Library().writeToFile("NewBooks.txt");
new Library().writeToFile("ErrorLines.txt");
}
#Override
public int compareTo(aBookList o) {
return 0;
}
}
as it is homework, i will point you direction, not give you code
1) you have lot of mess here, ie i'm not sure why you have compare in your main class? instead of creating getAll method in bookInfo(which is named against java nameing convention) just override toString method
2) why do you have list of strings? read a line, convert this into book, if book is valid add it to your list, otherwise report an error
3) move your isISBN13Valid method to book
4) write to file -> loop through your list, and save each element into file by bw.write(book.toString()),
5) create second method createErrorFile, then each error what you will have add into your error list, and after you call that method, you will sace each element into given file, it is not perfetc solution, better will be if you add error to file each time when it occur.
6) create one instance of library in your main method, and just call on it all your method, and avoid using static fields in your project(sometimes you must, but if you don;t need, just avoid them)
7) names for method import/ export i think sounds nicer than read from file read from file

How can i show it at first?

I wrote a simple java application, I have a problem please help me;
I have a file (JUST EXAMPLE):
1.TXT
-------
SET MRED:NAME=MRED:0,MREDID=60;
SET BCT:NAME=BCT:0,NEPE=DCS,T2=5,DK0=KOR;
CREATE LCD:NAME=LCD:0;
-------
and this is my source code
import java.io.IOException;
import java.io.*;
import java.util.StringTokenizer;
class test1 {
private final int FLUSH_LIMIT = 1024 * 1024;
private StringBuilder outputBuffer = new StringBuilder(
FLUSH_LIMIT + 1024);
public static void main(String[] args) throws IOException {
test1 p=new test1();
String fileName = "i:\\1\\1.txt";
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ";|,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
p.processToken(token);
}
}
p.flushOutputBuffer();
}
private void processToken(String token) {
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("MREDID:").append(value).append("\n");
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("DK0=:").append(value).append("\n");
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("NEPE:").append(value).append("\n");
}
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}
private String getTokenValue(String token,String find) {
int start = token.indexOf(find) + 1;
int end = token.length();
String value = token.substring(start, end);
return value;
}
private void flushOutputBuffer() {
System.out.print(outputBuffer);
outputBuffer = new StringBuilder(FLUSH_LIMIT + 1024);
}
}
I want this output :
MREDID:60
DK0=:KOR
NEPE:DCS
But this application show me this :
MREDID:60
NEPE:DCS
DK0=:KOR
please tell me how can i handle this , because of that DK0 must be at first and this is just a sample ; my real application has 14000 lines
Thanks ...
Instead of outputting the value when you read it, put it in a hashmap. Once you've read your entire file, output in the order you want by getting the values from the hashmap.
Use a HashTable to store the values and print from it in the desired order after parsing all tokens.
//initialize hash table
HashTable ht = new HashTable();
//instead of outputBuffer.append, put the values in to the table like
ht.put("NEPE", value);
ht.put("DK0", value); //etc
//print the values after the while loop
System.out.println("MREDID:" + ht.get("MREDID"));
System.out.println("DK0:" + ht.get("DK0"));
System.out.println("NEPE:" + ht.get("NEPE"));
Create a class, something like
class data {
private int mredid;
private String nepe;
private String dk0;
public void setMredid(int mredid) {
this.mredid = mredid;
}
public void setNepe(String nepe) {
this.nepe = nepe;
}
public void setDk0(String dk0) {
this.dk0 = dk0;
}
public String toString() {
String ret = "MREDID:" + mredid + "\n";
ret = ret + "DK0=:" + dk0 + "\n";
ret = ret + "NEPE:" + nepe + "\n";
}
Then change processToken to
private void processToken(String token) {
Data data = new Data();
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
data.setMredid(Integer.parseInt(value));
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
data.setDk0(value);
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
data.setNepe(value);
}
outputBuffer.append(data.toString());
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}

Categories

Resources