How to fix a Null Pointer Exception upon string retrieval - hash table - java

class Item
{
private int address;
private String itemString;
public Item(String item)
{
separate(item);
}
public void separate(String string)
{
StringTokenizer st = new StringTokenizer(string);
itemString = st.nextToken();
if(st.hasMoreTokens())
{
address = Integer.parseInt(st.nextToken());
}
else
{
address = -1;
}
}
public String getKey()
{
return itemString;
}
public int getAddress()
{
return address;
}
public void illegitimize()
{
itemString = "*del";
address = -1;
}
}
class HashTable
{
private Item[] hashArray;
private int arraySize;
public HashTable(int size)
{
arraySize = size;
hashArray = new Item[arraySize];
}
public int hash(Item item)
{
String key = item.getKey();
int hashVal = 0;
for(int i=0; i<key.length(); i++)
{
int letter = key.charAt(i) - 96;
hashVal = (hashVal * 26 + letter) % arraySize;
}
return hashVal;
}
public void insert(Item item)
{
int hashVal = hash(item);
while(hashArray[hashVal] != null &&
!(hashArray[hashVal].getKey().contains("*")))
{
hashVal++;
hashVal %= arraySize;
}
String keyAtHashVal = hashArray[hashVal].getKey();
String itemKey = item.getKey();
if(!keyAtHashVal.equals(itemKey))
{
hashArray[hashVal] = item;
System.out.println(item.getKey() + " inserted into the table at "
+ "position " + hashVal);
}
else
{
System.out.println("Error: " + item.getKey() + " already exists "
+ "at location " + hashVal);
}
}
public Item find(Item item)
{
int hashVal = hash(item);
while(hashArray[hashVal] != null)
{
if(hashArray[hashVal].getKey().equals(item.getKey()))
{
System.out.println(item.getKey() + " found at location "
+ hashVal + " with address " + item.getAddress());
return hashArray[hashVal];
}
hashVal++;
hashVal %= arraySize;
}
System.out.println("Error: " + item.getKey() + " not found in the "
+ "table");
return null;
}
}
public class HashTableMain
{
public static void main(String[] args) throws Exception
{
File file = new File(args[0]);
Scanner input = new Scanner(file);
Item currentItem;
String currentItemsKey;
int currentItemsAddress;
HashTable table = new HashTable(50);
while(input.hasNextLine())
{
currentItem = new Item(input.nextLine());
currentItemsKey = currentItem.getKey();
currentItemsAddress = currentItem.getAddress();
if(currentItemsAddress > 0)
{
table.insert(currentItem);
}
else
{
table.find(currentItem);
}
}
}
}
The title pretty much explains it. I get a null pointer when the insert() method attempts to retrieve the key of the first item I feed it from the file. I figure this has something to do with the way I retrieve store the string but I cannot identify the problem.
The records inside the file will be in this format:
george
stacy 112
patrick 234
angelo 455
money 556
kim
chloe 223
If there is a number in the line I need to hash the item into the array at the appropriate location. If there is no number I need to search for the key (the string at the beginning of each line).
Edit: added find function. I left out anything I didn't think you needed to help me. If you need anything else let me know.

The problem seems to be at
String keyAtHashVal = hashArray[hashVal].getKey();
in the HashTable.insert() . Your hashArray[hashVal] may not have an object in it leading to a null pointer. You could do a null check.
Item existingItem = hashArray[hashVal];
if(existingItem==null) {
//do appropriate code
} else {
//do your stuff
}
BTW, StringTokenizer is deprecated and is only there for compatibility purposes. You could use the String.split() method.
Plus instead of HashTable , you can use the HashMap if you are not aware of it

String keyAtHashVal = hashArray[hashVal].getKey();
The problem is is that hashArray[hashVal] is always going to be null because you probe for a null space in a previous statement. I suspect that it should be moved inside the while() loop and used there.

Related

Why does my output not match the expected output and how can I make it match?

here is a dictionary program.
Code Provided
import java.util.*;
public enum Dictionary {
DistinctADJECTIVEONE("Distinct","adjective","Familiar. Worked in Java."),
DistinctADJECTIVETWO("Distinct","adjective","Unique. No duplicates. Clearly different or of a different kind."),
DistinctADVERB("Distinct","adverb","Uniquely. Written 'distinctly.'"),
DistinctNOUNONE("Distinct","noun","A keyword in this assignment."),
DistinctNOUNTWO("Distinct","noun","A keyword in this assignment."),
DistinctNOUNTHREE("Distinct","noun","A keyword in this assignment."),
DistinctNOUNFOUR("Distinct","noun","An advanced search option."),
DistinctNOUNFIVE("Distinct","noun","Distinct is a parameter in this assignment.");
private final String generalNote = "Dictionary";
private String keyword;
private String partOfSpeech;
private String definition;
private Dictionary(String keyword, String partOfSpeech, String definition) {
this.keyword = keyword;
this.partOfSpeech = partOfSpeech;
this.definition = definition;
}
public String getKeyword() {
return this.keyword.toUpperCase();
}
public String definition(){
return this.definition;
}
#Override
public String toString() {
return this.keyword + " [" + this.partOfSpeech + "] : " + this.definition;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("! Loading data...");
HashMap<String, ArrayList<Dictionary>> hmap = new HashMap<String, ArrayList<Dictionary>>();
for (Dictionary dict : Dictionary.values()) {
String keyword = dict.getKeyword();
ArrayList<Dictionary> list = (hmap.containsKey(keyword)) ? hmap.get(keyword) : new ArrayList<Dictionary>();
list.add(dict);
hmap.put(keyword, list);
}
System.out.println("! Loading Complete...");
Boolean quite = true;
int counter = 7;
do {
counter++;
System.out.print("[" + counter + "] Search: ");
String userinput = input.nextLine();
String[] splited = userinput.split(" ");
String word = null;
Boolean requestDistinct = false;
if (splited.length > 0) {
word = splited[0];
}
if (splited.length > 1 && splited[1]!= null) {
if (splited[1].equalsIgnoreCase("distinct")) {
requestDistinct = true;
}
else {
System.out.println(" |");
System.out.println(" <The entered 2nd parameter " + userinput + " is NOT 'distinct'.>\n" +
" <The 2nd parameter should be a part of speech or 'distinct'.>");
System.out.println(" |");
continue;
}
}
if(!userinput.equalsIgnoreCase("!q")) {
System.out.println(" |");
ArrayList<Dictionary> result = hmap.get(word.toUpperCase());
ArrayList<Dictionary> secondResult = (requestDistinct) ? returnDictionaryWithDistinctDefinition(result) : result;
if (secondResult != null && secondResult.size()>0) {
for(Dictionary key : secondResult) {
System.out.print(" " + key + "\n");
}
}
System.out.println(" |");
} else {
System.out.println("\n----Thank You---");
quite = false;
}
requestDistinct = false;
} while(quite);
}
public static ArrayList<Dictionary> returnDictionaryWithDistinctDefinition(ArrayList<Dictionary> dictList) {
HashMap<String, Dictionary> hMap = new HashMap<String, Dictionary>();
if (dictList != null) {
for (Dictionary dict : dictList) {
String definition = dict.definition();
if (!hMap.containsKey(definition)) {
hMap.put(definition, dict);
}
}
}
return new ArrayList<Dictionary>(hMap.values());
}
}
The user can type in up to two arguments.
The first argument would be just 'Distinct' and the Dictionary would display all the definitions of distinct stored as Enums.
The second argument can be 'Distinct', which would display all the UNIQUE definitions.
So while my program does function as intended, why doesn't my output in photo #1 match up with the output shown in photo #2? (It went out of order) And how can this be fixed?
Photo #1 (My Output)
Photo #2 (The required output)
HashMap does not maintain insertion order. Please try using LinkedHashMap. LinkedHashMap maintains insertion order, and you will not see this issue.

Use the toString() method to print a numbered list of String Array objects

This is what I am trying to output:
Choose an option :
(1) Water
(2) Soda pop
(3) Beer
?-> Enter an option number :
This is my code:
public class Menu
{
private String[] optionList;
private String openingMessage;
private String topPrompt;
private String closingMessage;
private String bottomPrompt;
public Menu(String[] options)
{
optionList = options;
openingMessage = "";
topPrompt = "Choose an option:";
closingMessage = "";
bottomPrompt = "Enter an option number:";
}
public Menu()
{
optionList = null;
openingMessage = "";
topPrompt = "";
closingMessage = "";
bottomPrompt = "";
}
public boolean isEmpty(String[] options)
{
if (options == null)
{
return true;
}
return false;
}
public int length(String[] options)
{
return options.length;
}
public String toString()
{
return (topPrompt + "\n" + "?->" + " " + bottomPrompt);
}
public static void main(String[] args)
{
String[] drink_options = {"Water", "Soda pop", "Beer"};
Menu drinkMenu = new Menu(drink_options);
System.out.println(drinkMenu);
//System.out.println(drinkMenu.isEmpty(drink_options));
//System.out.println(drinkMenu.length(drink_options));
}
What will I have to do in the toString() method in order for the numbers in brackets to appear before each listing of the String array elements? I am thinking I could use the length() method to obtain the number n of elements inside the array and use a for loop to add the numbers in front.
Please let me know your insights.
Thank you!
Try something like:
public boolean isEmpty()
{
return options == null || options.length == 0
}
public int length()
{
return isEmpty() ? 0 : options.length;
}
public String toString()
{
String result = topPrompt + "\n";
for (i=0; i<lenth(); i++) {
result += "(" + (i+1)+ ") " + options[i];
}
result += "?->" + " " + bottomPrompt);
return result;
}

Sequential search does not work as expected

I have written a program which takes the words the user have entered, with a button press, and puts them in an ArrayList. There is also another text field where the user can enter a letter or word, for which the user can search for in the ArrayList with another button press. I'm using a sequential search algorithm to accomplish this, but it does not work as I expect it to; If the searched word is found, the search function should return, and print out in a textArea that the word was found and where in the array it was found. This works, but only for the first search. If the word is not found, the function should print out that the word was not found. This works as I want it to.
The problem is that after I searched for one word, and it displays where in the ArrayList this can be found, nothing happens when I press the button after that, whether the entered letter/word is in the array or not. It's like the string that the text gets stored isn't changing. I don't understand why... Here below is the custom Class of the search function and then my Main class:
public class Search {
static private int i;
static String index;
static boolean found = false;
public static String sequencial (ArrayList<String> list, String user) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
index = "The word " + user + " exist on the place " + i + " in the Arraylist";
found = true;
}
}
if (!found) {
index = "The word " + user + " could not be found";
}
return index;
}
My Main class:
ArrayList<String> list = new ArrayList<String>();
ArrayList<String> s = new ArrayList<String>();
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
txtaOutput.setText("");
String word = txtfAdd.getText();
list.add(word);
for (int i = 0; i < list.size(); i++) {
txtaOutput.append("" + list.get(i) + "\n");
}
}
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String user = txtfSearch.getText();
txtaOutput.setText("");
String index = Search.sequencial(list, user);
txtaOutput.setText("" + index);
}
Any help is appreciated!
The problem is that you declared your found variable as static. When your first word is found, it is set to true, and nothing ever sets it back to false. Instead of making it a static variable, declare it as a local variable inside your sequencial (it's spelled sequential, by the way) function, just before the for-loop.
In fact, all the variables you've declared as static should be made local. Declaring static variables is never a good idea.
As said by other users:
There is the List#indexOf(Object) method. You should use that instead of reinventing the wheel (unless you need to, and in that case you might have a look at the ArrayList implementation). There are also other collections, like HashSet which are more apropiate for looking up, but i guess that is another history.
The scope and the names of the variables (i, index, found) is error-prone. Do other methods or even classes need to have access to those variables? If you need to keep those variables, you might want to choose a visibility (public,protected,private). "index" is a misleading choice of a name for a message.
This would be an slightly simplified/corrected version of your code:
// Ommit those unneeded static variables
public static String sequencial (ArrayList<String> list, String user) {
int indexFound = list.indexOf(user);
if (user >= 0) {
return "The word " + user + " exist on the place " + indexFound + " in the Arraylist";
} else {
return "The word " + user + " could not be found";
}
}
...
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
String user = txtfSearch.getText();
// txtaOutput.setText("");
String seqMessage = sequencial(list, user);
txtaOutput.setText(seqMessage);
}
We use the static properties when you would like to use the constants. You should not use the static properties here. The problem will happen when your found property is changed the first time, it will not be changed again. And from that time, it will always be true. Similar with index property. Here is the code you can fix this:
public class Search {
public static SearchResult sequencial (ArrayList<String> list, String user) {
SearchResult result = null;
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(user)) {
String index = "The word " + user + " exist on the place " + i + " in the Arraylist";
boolean found = true;
result = new SearchResult(index, found);
break;
}
}
if (result == null) {
String index = "The word " + user + " could not be found";
result = new SearchResult(index);
}
return result;
}
//sample inner class
static class SearchResult {
private String index;
private boolean found;
public SearchResult(String index) {
this.index = index;
}
public SearchResult(String index, boolean found) {
this.index = index;
this.found = found;
}
public String getIndex() {
return index;
}
public void setIndex(String index) {
this.index = index;
}
public boolean isFound() {
return found;
}
public void setFound(boolean found) {
this.found = found;
}
}
}
public class SequencialSearcher {
public static int SequencialSearchInt(int[] inputArray, int key)
{
for(int i=0; i < inputArray.length ; i++)
{
if(inputArray[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchString(String[] array, String key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static int SequencialSearchFloat(double[] array, double key)
{
for(int i=0; i < array.length ; i++)
{
if(array[i] == key)
{
return i;
}
}
return -1;
}
public static void main (String args[])
{
//select the type of the elements of search
//1 if integers
//2 if float
//3 if string
int x = 3;
int[] array1 = {9, 0, 10, 8, 5, 4, 6, 2, 3};
double[] array2 = {9.0, 0.0, 10.0, 8.0, 5.0, 4.0, 6.0, 2.0, 3.0};
String[] array3 = {"aa","hey", "hello"};
if(x == 1){
//enter the integer you want to search for here below
int requiredValue = 5;
int result = SequencialSearchInt(array1, requiredValue);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue+" not found");
}
}
else if(x == 2)
{
//enter the double you want to search for here below
double requiredValue1 = 5.0;
int result = SequencialSearchFloat(array2, requiredValue1);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue1+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue1+" not found");
}
}
else if(x == 3){
//enter the string you want to search for here below
String requiredValue2 = "hey";
int result = SequencialSearchString(array3, requiredValue2);
if (result != -1)
{
System.out.println("Required Value: "+requiredValue2+" found at index: "+result);
}
else
{
System.out.println("Value:"+requiredValue2+" not found");
}
}
else{
System.out.println("Error. Please select 1,2 and 3 only");
}
}
}

CompareTo bubble sort

I am attempting to sort the values in my program using the Bubble Sort method. I believe that my code in the organisedRoom method is correct. However when I run the code, add some customers and then attempt to sort them, the program crashes. If anyone can please point me in the right direction I would greatly appreciate it.
package test;
import java.io.IOException;
import java.util.Scanner;
public class Test {
private class Customer implements Comparable<Customer>{
private String name;
public Customer(String name) {
this.name = name;
}
//Override to stop the program returning memory address as string
#Override
public String toString() {
return name;
}
#Override
public int compareTo(Customer c) {
return name.compareTo(c.name);
}
}
//Array to store customers
public Customer[] customers;
public Scanner input = new Scanner(System.in);
public Test(int nRooms) throws IOException {
customers = new Test.Customer[nRooms];
System.out.println("Welcome to the Summer Tropic Hotel\n");
chooseOption();
}
final JFileChooser fc = new JFileChooser();
// Call new Hotel with int value to allocate array spaces
public static void main(String[] args) throws IOException {
Test t = new Test(11);
}
// New procedure to return User input and point to next correct method
private String chooseOption() throws IOException {
// Set to null, this will take user input
String choice;
//Menu options
System.out.println("This is the Hotel Menu. Please choose from the following options:\n");
System.out.println("A: " + "This will add a new entry\n");
System.out.println("O: " + "View booked rooms, in order of customers name.\n");
System.out.println("X: " + "Exit the program\n");
// Take user input and assign it to choice
choice = input.next();
// Switch case used to return appropriate method
switch (choice.toUpperCase()) {
case "A" :
System.out.println("");
addCustomer();
return this.chooseOption();
case "O" :
System.out.println("");
organisedRoom();
return this.chooseOption();
case "X":
System.exit(0);
}
return choice;
}
// Add a new customer to the Array
public void addCustomer() throws IOException {
// New variable roomNum
int roomNum = 1;
// Loop
do {
// Take user input as room number matching to array index - 1
System.out.println("Please choose a room from 1 to 10");
roomNum = input.nextInt() - 1;
// If room is already booked print this
if (customers[roomNum] != null) {
System.out.println("Room " + roomNum + 1 + " is not free, choose a different one.\n");
this.addCustomer();
}
// Do until array index does not equal to null
} while (customers[roomNum]!= null);
System.out.println("");
// User input added to array as name replacing null (non case-sensetive)
System.out.println("Now enter a name");
customers[roomNum] = new Customer(input.next().toLowerCase());
// Customer (name) added to room (number)
System.out.println(String.format("Customer %s added to room %d\n", customers[roomNum], roomNum + 1));
}
private void organisedRoom() {
boolean flag = true;
Customer temp;
int j;
while (flag) {
flag = false;
for (j = 0; j < customers.length - 1; j++) {
if (customers[j].compareTo(customers[j+1]) < 0) {
temp = customers[j];
customers[j] = customers[j + 1];
customers[j + 1] = temp;
flag = true;
}
}
}
}
}
I think this is because the initialisation of the array adds null to all the array index places.
The stack trace is as follows:
Exception in thread "main" java.lang.NullPointerException
at test.Test$Customer.compareTo(Test.java:34)
at test.Test.organisedRoom(Test.java:133)
at test.Test.chooseOption(Test.java:83)
at test.Test.chooseOption(Test.java:79)
at test.Test.chooseOption(Test.java:79)
at test.Test.<init>(Test.java:46)
at test.Test.main(Test.java:55)
Java Result: 1
It fails because you create Customer[] which will be initialized with11 null references. If you want to order them all elements in the array will be compared. Which lead into the java.lang.NullPointerException.
Store the Customer in an ArrayList. Then you should be able to prevent this error.
edit
If you really need to stick as close as possible to your current code. The following would fix your sorting. (don't use this solution for a real life project)
private void organisedRoom() {
for (int i = customers.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (customers[j + 1] == null) {
continue;
}
if (customers[j] == null ||customers[j + 1].compareTo(customers[j]) < 0) {
Customer temp = customers[j + 1];
customers[j + 1] = customers[j];
customers[j] = temp;
}
}
}
System.out.println("show rooms: " + Arrays.toString(customers));
}
edit 2
To keep most of your current code, you might store the room in the Customer instance (which I personally would not prefer).
// change the constructor of Customer
public Customer(String name, int room) {
this.name = name;
this.room = room;
}
// change the toString() of Customer
public String toString() {
return String.format("customer: %s room: %d", name, room);
}
// store the Customer like
customers[roomNum] = new Customer(input.next().toLowerCase(), roomNum);
Your implementation of Bubble Sort is incorrect. It uses nested for loops.
for(int i = 0; i < customers.length; i++)
{
for(int j = 1; j < (customers.length - i); j++)
{
if (customers[j-1] > customers[j])
{
temp = customers[j-1];
customers[j-1] = customers[j];
customers[j] = temp;
}
}
}

Why is this not reading my file?

I'm having problems getting my program to read an input file from the same directory.
code is in Main, included the whole just incase i have done something outside of main that is causing this.
import java.io.*;
import java.util.*;
public class Final
{
public static int readData(BusinessDirectory [] array, Scanner input,Scanner inputFile)
{
int lastChar = 0;
int count =0;
int dirChoice = 0;
int area,
exchange,
number,
extension;
String name;
while(inputFile.hasNextLine() && count < array.length)
{
String Og = inputFile.nextLine();
lastChar = (Og.length()-1);
dirChoice = Integer.parseInt(Og.substring(0,1));
if(dirChoice == 1)
{
area = Integer.parseInt(Og.substring(2,5));
exchange = Integer.parseInt(Og.substring(6,9));
number = Integer.parseInt(Og.substring(10,14));
name = Og.substring(15,lastChar);
array[count].DirectorySet(area, exchange, number, name);
}
if(dirChoice == 2)
{
area = Integer.parseInt(Og.substring(2,5));
exchange = Integer.parseInt(Og.substring(6,9));
number = Integer.parseInt(Og.substring(10,14));
extension = Integer.parseInt(Og.substring(15,19));
name = Og.substring(20,lastChar);
array[count].BusinessDirectorySet(area, exchange, number, extension, name);
}
}
return count;
}
public static void main(String[]args)throws IOException
{
String infile;
int count=0;;
//Directory[]array = new Directory[25];
BusinessDirectory[]array = new BusinessDirectory[25];
Scanner in = new Scanner(System.in);
System.out.print("What is the input file: ");
infile = in.next();
try
{
File inputFile = new File(infile);
Scanner fin = new Scanner(inputFile);
readData(array, in, fin);
System.out.println(BusinessDirectory.getName());
// System.out.println("test");
//count = readData(array,in,inputFile);
}
catch(Exception e)
{
System.out.println("\"" + infile + "\" not found. Program will terminate.");
System.exit(0);
}
}
}
it always throws the Exception from the Catch.
("test.txt" not found. Program will terminate.)
e.printStackTrace();
gets me
What is the input file: test.txt
java.lang.NullPointerException
"test.txt" not found. Program will terminate.
at Final.readData(Final.java:36)
at Final.main(Final.java:69)
Error seems to be in my Directory Class
public class Directory
{
//data members
static int Area;
static int Exchange;
static int Number;
static String Name;
static int cause;
public Directory()
{
Area = 999;
Exchange = 999;
Number = 9999;
Name = "";
cause = 0;
}
public Directory(int area, int exchange, int number, String name)
{
DirectorySet(number, number, number, name);
}
public void DirectorySet(int area, int exchange, int number, String name)
{
try
{
if(area >= 200 && area <= 999 && area != 911)
{
if(exchange >= 200 && exchange <= 999 && exchange !=911)
{
if(number >= 0 && number <= 9999)
{
Area = area;
Exchange = exchange;
Number = number;
Name = name;
}else
{
cause = 1;
MyOwnException error = new MyOwnException();
MyOwnException.Message = error.setMessage(cause);
throw error;
}
}else if(exchange == 911 || area == 911)
{
cause = 4;
MyOwnException error = new MyOwnException();
MyOwnException.Message = error.setMessage(cause);
throw error;
}
cause = 2;
MyOwnException error = new MyOwnException();
MyOwnException.Message = error.setMessage(cause);
throw error;
}else
{
cause = 3;
MyOwnException error = new MyOwnException();
MyOwnException.Message = error.setMessage(cause);
throw error;
}
}
catch(MyOwnException error)
{
System.out.println(toString());
System.out.println(MyOwnException.Message);
//System.out.println(Directory.toString());
}
}
public void toString(int area, int exchange, int number, String name)
{
System.out.println(name + " (" + area + ") " + exchange + " -" + number);
}
public String toString()
{
return (Name + " (" + Area + ") " + Exchange + " -" + Number);
}
public static String getName()
{
return Name;
}
public static int getArea()
{
return Area;
}
public static int getExchange()
{
return Exchange;
}
public static int getNumber()
{
return Number;
}
public void setName(String name)
{
Name = name;
}
public void setArea(int area)
{
Area = area;
}
public void setExchange(int exchange)
{
Exchange = exchange;
}
public void setNumber(int number)
{
Number = number;
}
}
..
Final.readData(Final.java:37)
array[count].DirectorySet(area, exchange, number, name);
Final.main(Final.java:73)
readData(array, fin);
Your NullPointerException seems to be thrown at this line :
array[count].DirectorySet(area, exchange, number, name);
The problem is that you correctly created the array this way :
BusinessDirectory[]array = new BusinessDirectory[25];
But that creates only the space for 25 object pointers, that doesn't actually creates 25 objects.
You have to create each object one by one, in your case you should probably do this :
array[count] = new Directory(area, exchange, number, name);
instead of this :
array[count].DirectorySet(area, exchange, number, name);
Also you don't seem to increment count anywhere.
Try:
File inputFile = new File(infile);
System.out.println(inputFile.getAbsolutePath());
This will give you a hint about your working directory and you can fix your input (absolute or relative paths)
Also it is recommended that if you're not sure about the relative location and do not wish to use absolute paths, use the File.exists() API to make a decision within your code.

Categories

Resources