Why is this not reading my file? - java

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.

Related

Can't loop properly through list of objects

I'm having the following issue.
I have a list filled with instances of the "God" class, 12 instances, for now, but will add more in the future.
I also have an list empty.
Both lists can take type God instances.
The user will pick 6 of these gods, and these gods will be added to the empty list, and also be remove of the filled list, so they can't get picked again.
The goal of this part of the project is, to:
The user will pick 6 times. So I have a for loop from 0 to 5;
The Scanner takes the id of the god
The second for loop, from 0 to listFilledWithGods.size(), will check if the scanner matches the id
If the id matches, it will add to the empty list, and remove from the List filled with gods
If it does not match the user needs to be asked constantly to pick another one, until the user picks an available god. (here is where I'm having trouble)
Github: https://github.com/OrlandoVSilva/battleSimulatorJava.git
The issue in question resides in the class player in the method selectGodsForTeam
There is a JSON jar added to the project: json-simple-1.1.1
*Edit:
I added the while loop, as an exmaple of one of the ways that I tried to fix the issue.
If the user on the first pick picks id 3, it should work, because no god has been picked yet, however the loop when comparing it with the first position (id 1) it says to pick another one, which should is not the intended objective.
Main:
import java.util.List;
public class Main {
public Main() {
}
public static void main(String[] args) {
Launcher launch = new Launcher();
godSelection(launch.loadGods());
}
private static void godSelection(List<God> listOfloadedGods) {
Player player = new Player(listOfloadedGods);
player.selectGodsForTeam();
}
}
Launcher:
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Launcher {
private List<God> godCollection;
public Launcher(){
godCollection = new ArrayList<>();
}
List<God> loadGods(){ // load all gods from Json file into list
String strJson = getJSONFromFile("C:\\Users\\OrlandoVSilva\\Desktop\\JavaBattleSimulator\\battlesimulator\\src\\projectStructure\\gods.json");
// Try-catch block
try {
JSONParser parser = new JSONParser();
Object object = parser.parse(strJson); // converting the contents of the file into an object
JSONObject mainJsonObject = (JSONObject) object; // converting the object into a json object
//-------------------
JSONArray jsonArrayGods = (JSONArray) mainJsonObject.get("gods");
//System.out.println("Gods: ");
for(int i = 0; i < jsonArrayGods.size(); i++){
JSONObject jsonGodsData = (JSONObject) jsonArrayGods.get(i);
String godName = (String) jsonGodsData.get("name");
//System.out.println("Name: " + godName);
double godHealth = (double) jsonGodsData.get("health");
//System.out.println("Health: " + godHealth);
double godAttack = (double) jsonGodsData.get("attack");
//System.out.println("Attack: " + godAttack);
double godSpecialAttack = (double) jsonGodsData.get("specialAttack");
//System.out.println("Special Attack: " + godSpecialAttack);
double godDefense = (double) jsonGodsData.get("defense");
//System.out.println("Defense: " + godDefense);
double godSpecialDefence = (double) jsonGodsData.get("specialDefense");
//System.out.println("Special Defence: " + godSpecialDefence);
double godSpeed = (double) jsonGodsData.get("speed");
//System.out.println("Speed: " + godSpeed);
double godMana = (double) jsonGodsData.get("mana");
//System.out.println("Mana: " + godMana);
String godPantheon = (String) jsonGodsData.get("pantheon");
//System.out.println("Pantheon: " + godPantheon);
long godId = (long) jsonGodsData.get("id");
int newGodId = (int) godId;
//System.out.println("Id: " + newGodId);
godCollection.add(new God(godName, godHealth, godAttack, godSpecialAttack, godDefense, godSpecialDefence, godSpeed, godMana, godPantheon, newGodId));
//System.out.println();
}
} catch (Exception ex){
ex.printStackTrace();
}
// Try-catch block
//System.out.println("Size: " + godCollection.size());
return godCollection;
}
public static String getJSONFromFile(String filename) { // requires file name
String jsonText = "";
try {
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename)); // read the file
String line; // read the file line by line
while ((line = bufferedReader.readLine()) != null) {
jsonText += line + "\n"; // store json dat into "jsonText" variable
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
}
return jsonText;
}
}
Player:
import java.util.*;
public class Player {
// --- Properties ---
private List<God> listOfAllGods; // List of all the gods;
private List<God> selectedGods; // list for the selected gods;
// --- Properties ---
// --- Constructor ---
Player(List<God> listOfAllGods){
this.listOfAllGods = listOfAllGods;
selectedGods = new ArrayList<>();
}
// --- Constructor ---
// --- Getters & Setters ---
public List<God> getSelectedGods() {
return listOfAllGods;
}
// --- Getters & Setters ---
// --- Methods ---
void selectGodsForTeam(){
Scanner scanner = new Scanner(System.in);
boolean isGodAvailable;
int chooseGodId;
/*
char answerChar = 'n';
while (answerChar == 'n'){
answerChar = informationAboutGods();
// Do you want to see information about any of the gods first?
// y or n
while(answerChar == 'y'){
answerChar = informationAboutAnyOtherGods();
// Which of the gods, do you want to see information of?
// godId
// Do you want to see information about any other gods?
// y or n
}
answerChar = proceedWithGodPick();
// Do you want to proceed with the God pick?
// y or n
}
System.out.println();
*/
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
for(int i = 0; i <= 5; i++){
chooseGodId = scanner.nextInt();
for(int j = 0; j < listOfAllGods.size(); j++){
if(chooseGodId == listOfAllGods.get(j).getId()){
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
} else {
isGodAvailable = false;
while (!isGodAvailable){
System.out.println("Please pick another one");
chooseGodId = scanner.nextInt();
if(chooseGodId == listOfAllGods.get(j).getId()) {
isGodAvailable = true;
selectedGods.add(listOfAllGods.get(j));
listOfAllGods.remove(j);
}
}
}
}
}
}
char informationAboutGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//-----------
System.out.println("This is a list, of all the selectable gods: ");
System.out.println();
for (int i = 0; i < listOfAllGods.size(); i++){
System.out.println(listOfAllGods.get(i).getName() + " = " + "Id: " + listOfAllGods.get(i).getId());
}
System.out.println();
System.out.println("Do you want to see information about any of the gods first?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char informationAboutAnyOtherGods(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
int answerInt;
//------------
System.out.println();
System.out.println("Which of the gods, do you want to see information of?");
System.out.println("Please input it's id number: ");
answerInt = scanner.nextInt();
System.out.println();
System.out.println("Display god information here!");
System.out.println();
System.out.println("Do you want to see information about any other gods?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
char proceedWithGodPick(){
Scanner scanner = new Scanner(System.in);
char answerChar = 'n';
//----------
System.out.println();
System.out.println("Do you want to proceed with the God pick?");
System.out.println("[y] or [n]");
answerChar = scanner.next().charAt(0);
return answerChar;
}
// --- Methods ---
}
God:
public class God {
private final String name;
private double health;
private double attack;
private double specialAttack;
private double defense;
private double specialDefense;
private double speed;
private double mana;
private final String pantheon;
private final int id;
public God(String name, double health, double attack, double specialAttack, double defense, double specialDefense, double speed, double mana, String pantheon, int id) {
this.name = name;
this.health = health;
this.attack = attack;
this.specialAttack = specialAttack;
this.defense = defense;
this.specialDefense = specialDefense;
this.speed = speed;
this.mana = mana;
this.pantheon = pantheon;
this.id = id;
}
public double getHealth() {
return this.health;
}
public void setHealth(double health) {
this.health = health;
}
public double getAttack() {
return this.attack;
}
public void setAttack(double attack) {
this.attack = attack;
}
public double getSpecialAttack() {
return this.specialAttack;
}
public void setSpecialAttack(double specialAttack) {
this.specialAttack = specialAttack;
}
public double getDefense() {
return this.defense;
}
public void setDefense(double defense) {
this.defense = defense;
}
public double getSpecialDefense() {
return this.specialDefense;
}
public void setSpecialDefense(double specialDefense) {
this.specialDefense = specialDefense;
}
public double getSpeed() {
return this.speed;
}
public void setSpeed(double speed) {
this.speed = speed;
}
public double getMana() {
return this.mana;
}
public void setMana(double mana) {
this.mana = mana;
}
public String getName() {
return this.name;
}
public String getPantheon() {
return this.pantheon;
}
public int getId() {
return this.id;
}
}
If I understand correctly, the key is to replace the for loop, which will have 6 iterations, with a while loop, which will iterate until the user has successfully selected 6 gods. Use continue; when there is a failure to select a god.
System.out.println("Please choose the 6 id's of the gods, you wish to pick:");
while (selectedGods.size () < 6) {
System.out.print ("You have selected " + selectedGods.size ()
+ "gods. Please enter I.D. of next god >");
chooseGodId = scanner.nextInt();
if (findGod (selectedGods, chooseGodID) >= 0) {
System.out.println ("You already selected god " + chooseGodId
+ ". Please select again.");
continue;
}
int godSelectedIndex = findGod (listOfAllGods, chooseGodId);
if (godSelectedIndex < 0) {
System.out.println ("God " + chooseGodID + " is not available."
+ " Please select again.");
continue;
}
selectedGods.add (listOfAllGods.get(godSelectedIndex));
listOfAllGods.remove (godSelectedIndex);
}
This assumes the existence of
static public int findGod (List<God> godList, int targetGodID)
This findGod method searches godList for an element in which .getId() is equal to gargetGodID. When a match is found, it returns the index of element where the match was found. When a match is not found, it returns -1. The O/P has shown the ability to create this method.
Note: I have not verified the code in this answer. If you find an error, you may correct it by editing this answer.

My toString() method isn't working and I can't figure out why, does anybody know whats happening

I'm trying to make a program that can tell whether or not a person needs to get a flu test based on their temperature and number of symptoms, but for some reason my toString() method refuses to work. I just need somebody to tell me why the toString() method refuses to work. The output of this code should be:
"Alice should be tested for the flu due to her 102 F temperature and aching muscles and fatigue."
when all I get as an output is:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 21, end 27, length 26
at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3319)
at java.base/java.lang.String.substring(String.java:1874)
at FluDiagnoser.<init>(FluDiagnoser.java:20)
at Main.main(Main.java:5)
Main.java:
public class Main
{
public static void main(String[] args)
{
FluDiagnoser tester = new FluDiagnoser("Alice", 23, 102, "aching muscles and fatigue");
System.out.println(tester);
}
}
FluDiagnoser.java:
public class FluDiagnoser {
private int age;
private String name;
private double temp;
private String symptoms;
int x = 0;
int symptCount = 0;
int andFix = 5;
public FluDiagnoser(String name, int age, double temp, String symptoms) {
this.name = name;
this.age = age;
this.temp = temp;
this.symptoms = symptoms;
int symptL = symptoms.length();
for (int i = 0; i < symptL; i++) {
String commaStr = symptoms.substring(i, i + 2);
String andStr = symptoms.substring(i, i + andFix);
String cAndStr = symptoms.substring(i, i + 6);
if (commaStr.equals(", ") && !cAndStr.equals(", and ")) {
symptCount += 1;
} else if (andStr.equals(" and ")) {
symptCount += 2;
} else if (cAndStr.equals(", and ")) {
andFix = 2;
symptCount += 2;
} else {
symptCount = symptCount;
}
}
if (symptCount >= 2) {
x++;
} else {
x = x;
}
if (temp > 100.4) {
x++;
} else {
x = x;
}
}
public void changeSymptoms(String change) {
symptoms = change;
}
public String getSymptoms() {
return symptoms;
}
public String toString() {
if (x >= 2) {
return name + " should be tested for the flu due to their " + temp + " F tempurature and " + symptoms + ".";
} else {
return name + " doesn't need to be tested for the flu.";
}
}
}
I don't understand what's happening to make this program not work

My ArrayList is not returning the correct output (must write file directory to csv file)

I'm doing a java program that prints a file directory on my computer. I have 3 classes, the MyFile class (to write to the file), the ListFiles class (to retrieve the files and attributes of the directory), and the Folder class (to create a folder object of the specific directory address). My output produces everything correctly, except for the fact that it does not write to my csv file and my minimum and maximum are either the same or the minimum is 0. I have only been programming java for 8 months, so i'm sure it's an easy solution to most people, but for me I'm not sure where to even start with my logic error. I appreciate all input and thank you! Here's my code.
I have created three arraylists to retrieve the contents of my directory and essentially write it to the csv file, I have also attempted initializing my minimum and maximum variables to different values in order to get the correct size.
public class ListFiles {
ArrayList<Folder> theFolder = new ArrayList();
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
///call ListFiles
new ListFiles();
}
////ListFiles method to print whether it exists
public ListFiles() {
String dname = JOptionPane.showInputDialog("Please enter a path for folder: ");
File f = new File(dname);
if (f.exists()) {
System.out.println("Exists");
showFiles(dname, " ");
ArrayList<String> callShowFiles = showFiles(dname, " ");
ArrayList<Folder> callGetDirectoryInfo = getDirectoryInfo(callShowFiles);
ArrayList<String> callGetFolderInfo = getFolderInfo(callGetDirectoryInfo);
MyFile.myFileWriter(callGetFolderInfo, "FileDirectory.csv");
} else {
System.out.println("Does not exist");
}
}
///show files (find child file name, parent file name, extensions, subfolder count, min, max, and avg of files
public ArrayList<String> showFiles(String dirName, String idn) {
System.out.println("START ------------------------");
//create indent
String indent = idn;
///create new file for direcctory name
File file = new File(dirName);
///create index for dirName (lastIndexOf) to print out the last thing
int index = dirName.lastIndexOf('\\');
///get and print name of parent file
File fileParent = file.getParentFile();
Folder folder = new Folder(dirName.substring(index + 1));
folder.setParent(fileParent.getPath());
int indexForParent = folder.getParent().lastIndexOf("\\");
folder.parent = folder.getParent().substring(indexForParent);
///find amount of subfolders
if (file.isDirectory()) {
folder.folderCount = file.list().length;
System.out.println("Subfolder Count:" + folder.folderCount);
///folder.name = name
folder.name = name;
String[] files = file.list();
for (int i = 0; i < files.length; i++) {
File childFile = new File(dirName + "\\" + files[i]);
//int folderCount, int max, int avg, int min, String parent, String name, int totalSize, int fileCount, int xl, int ppt, int doc
if (childFile.isDirectory()) {
showFiles(dirName + "\\" + files[i], indent + " ");
} else {
///if the file count is 0, it is a file
}
if (folder.fileCount == 0) {
folder.fileCount++;
///set size to length of childfile
int size = (int) childFile.length();
///set min, max, and totalsize to size
folder.min = size;
folder.max = size;
folder.totalSize = size;
///if max is less than current size, max = size
if (folder.getMax() < size) {
folder.setMax(size);
// folder.fileCount++;
///if min is greater than current size, min == size
} else if (folder.getMin() > size) {
folder.setMin(size);
//folder.fileCount++;
} else {
////else fileCount increases and totalSIze increases
folder.fileCount++;
//folder.totalSize += size;
}
}
}
}
String folders =("Name: "+folder.name+"\nParent: "+ folder.parent+"\nFolder Count: "+ folder.folderCount+"\nFile Count: "+ folder.fileCount
+"\nTotal Size: "+folder.totalSize+"\nMin: "+ folder.min+"\nMax: "+folder.max+"\nAvg: "+ folder.avg
+"\nDocs: "+folder.doc+"\nXl: "+ folder.xl+"\nPpt: "+ folder.ppt);
ArrayList <String> print = new ArrayList();
print.add(folders);
System.out.println("END ------------------------\n");
return print;
}
public ArrayList<Folder> getDirectoryInfo(ArrayList<String> list){
ArrayList<Folder> emp = new ArrayList();
for(int i = 1; i< list.size(); i++){
String str = list.get(i);
String fields[] = str.split(",");
Folder e =new Folder(fields[0].trim(),
fields[1].trim(),
Integer.parseInt(fields[2].trim()),Integer.parseInt(fields[3].trim()),Integer.parseInt(fields[4].trim()),
Integer.parseInt(fields[5].trim()),Integer.parseInt(fields[6].trim()),Integer.parseInt(fields[7].trim()),
Integer.parseInt(fields[8].trim()),Integer.parseInt(fields[9].trim()),Integer.parseInt(fields[10].trim()));
emp.add(e);
}
///takes a string arraylist and returns folder list of fields to be wrote to csv file
return emp;
}
public ArrayList<String> getFolderInfo(ArrayList<Folder> emp){
ArrayList<String> stringFiles = new ArrayList();
stringFiles.add("Testing");
for(int i = 0; i < emp.size(); i++){
String str = emp.get(i).getName() + " , " +emp.get(i).getParent() + " , " + emp.get(i).getFolderCount() + " , "+emp.get(i).getFileCount()
+ " , " + emp.get(i).getTotalSize()+" , "+emp.get(i).getMin()+" , "+emp.get(i).getMax()
+" , "+emp.get(i).getAvg() + " , "+emp.get(i).getDoc() + " , "+emp.get(i).getXl()+" , "+emp.get(i).getPpt();
stringFiles.add(str);
System.out.println(str);
}
return stringFiles;
}
}
Here is my folder class
public class Folder {
String name;
String parent;
int folderCount;
int fileCount;
int totalSize;
int min, max, avg;
int doc, xl, ppt;
public Folder(String name) {
this.name = name;
}
public Folder(String name, String parent, int folderCount, int fileCount, int totalSize, int min, int max, int avg, int doc, int xl, int ppt) {
this.name = name;
this.parent = parent;
this.folderCount = folderCount;
this.fileCount = fileCount;
this.totalSize = totalSize;
this.min = min;
this.max = max;
this.avg = avg;
this.doc = doc;
this.xl = xl;
this.ppt = ppt;
}
public int getFileCount() {
return fileCount;
}
public void setFileCount(int fileCount) {
this.fileCount = fileCount;
}
public int getTotalSize() {
return totalSize;
}
public void setTotalSize(int totalSize) {
this.totalSize = totalSize;
}
public int getDoc() {
return doc;
}
public void setDoc(int doc) {
this.doc = doc;
}
public int getXl() {
return xl;
}
public void setXl(int xl) {
this.xl = xl;
}
public int getPpt() {
return ppt;
}
public void setPpt(int ppt) {
this.ppt = ppt;
}
public int getFolderCount() {
return folderCount;
}
public void setFolderCount(int folderCount) {
this.folderCount = folderCount;
}
public int getMin() {
return min;
}
public void setMin(int min) {
this.min = min;
}
public int getMax() {
return max;
}
public void setMax(int max) {
this.max = max;
}
public int getAvg() {
return avg;
}
public void setAvg(int avg) {
this.avg = avg;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And here is my MyFile Class (I'm 100% sure the code for this is correct though, it
should be an error in ListFiles)
public class MyFile {
public static ArrayList myFileReader(String fname) {
ArrayList<String> myList = new ArrayList();
try {
File file = new File(fname);
BufferedReader br = new BufferedReader(new FileReader(fname));
String st;
while ((st = br.readLine()) != null) {
myList.add(st);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
return myList;
}
public static void myFileWriter(ArrayList<String> list, String fname){
try {
File file = new File(fname);
PrintWriter pw = new PrintWriter(fname);
for(int i = 0; i < list.size(); i++){
pw.println(list.get(i));
}
pw.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
I expect it to print all of the fields/output of my file directory (parent, name, total size, folder count, min/max, etc.) to the .csv file and for the minimum size to be smaller than the maximum size. The only thing wrote to my.csv file is 'Testing' and my minimum size is the same as my maximum size or 0, even with multiple files in the directory.

I don't know where my String index out of range: 0 error is coming from

I'm trying to take data out of a txt file and create comparable objects out of the data and add them to an array. After that array is created, I want to make a 2d array that stores a 1 in a slot if two options meet the requirements. I keep getting a String index out of range: 0 error though and I do not know where it comes from.
import java.util.*;
import java.io.*;
public class CourseScheduler
{
public int numberOfCourses;
public int[][] adjacent;
public Course[] courses;
public CourseScheduler(String filename)
{
File file = new File(filename);
try{
Scanner scan = new Scanner(file);
numberOfCourses = scan.nextInt();
courses = new Course[numberOfCourses];
adjacent = new int[numberOfCourses][numberOfCourses];
scan.useDelimiter(",|\\n");
for(int i = 0; i < numberOfCourses;i ++){
if(scan.hasNext()){
String dept = scan.next();
String num = scan.next();
String building = scan.next();
String room = scan.next();
String instruct = scan.next();
courses[i] = new Course(dept, num, building, room, instruct);
}
}
}
catch(FileNotFoundException ex){
System.out.println("File was not found");
}
for(int x = 0;x<numberOfCourses;x++){
for(int y = 0;y<numberOfCourses;y++){
adjacent[x][y] = (courses[x].compare(courses[y]));
}
}
}
This is the code for the main class
public class Course{
String department;
String courseNum;
String buildingCode;
String roomCode;
String instructorName;
public Course(String dept, String number, String building, String room, String instructor){
department = dept;
courseNum = number;
buildingCode = building;
roomCode = room;
instructorName = instructor;
}
public String getDept(){
return department;
}
public String getCourse(){
return courseNum;
}
public String getBuilding(){
return buildingCode;
}
public String getRoom(){
return roomCode;
}
public String getInstructor(){
return instructorName;
}
public String toString(){
return department + ";" + courseNum + ";" + buildingCode + ";" + roomCode + ";" + instructorName;
}
public int compare(Course comp){
int ans = 1;
String compNum = comp.getCourse();
if(instructorName == comp.getInstructor())
ans = 0;
if(buildingCode == comp.getBuilding()){
if(roomCode == comp.getRoom())
ans = 0;
}
if(department == comp.getDept()){
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
}
return ans;
}
}
this is the code for the course class
Educated guess: Most likely your error is coming from this line:
if(courseNum.charAt(0) == compNum.charAt(0))
ans = 0;
Either courseNum or compNum are empty.
I did not try to compile and run it but its seems that the exception comes from this line
if(courseNum.charAt(0) == compNum.charAt(0))
If a string is empty, charAt(0) will throw exactly the given exception.
Tip: if you don't know how to use a debugger, use the old fashioned System.out.println(). Put println() here and there in your code to understand how it works.

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

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.

Categories

Resources