so I'm trying to make a greedy/jewel heist algorithm in java. I saved the numbers and weights for the jewels to a .txt file. My program is correctly reading the .txt file and I've written a program that can successfully read them. these are the numbers from my .txt file
575 - bag limit
125 3000 (weight, value)
50 100
500 6000
25 30
The problem I'm running into is that I'm struggling to add weights and values to the program. ideally the program would read the tuples and assign them keys and values. I tried to use a hashmap and a regular Map but they haven't been working. possibly because they're in the wrong place. I included both attempted maps and have them commented out like in my program. Would love some help on assigning these values so I can move on to the next step. thanks!!
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
// import java.util.HashMap;
// import java.util.Map;
public class readstringastext {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new
BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String weightLimit = Files.readAllLines(Paths.get("test.txt")).get(0);
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
HashMap<String, String> map = new HashMap<String, String>();
//
// for (String string : pairs) {
// String[] keyValue = string.split(" ");
// map.put(keyValue[0], keyValue[1]);
// System.out.println(keyValue);
// };
//final class MyEntry<K, V> implements Map.Entry<K, V> {
// private final K key;
// private V value;
//
// public MyEntry(K key, V value) {
// this.key = key;
// this.value = value;
// }
// #Override
// public K getKey() {
// return key;
// }
//
// #Override
// public V getValue() {
// return value;
// }
//
// #Override
// public V setValue(V value) {
// V old = this.value;
// this.value = value;
// return old;
// }
// Map.Entry<String, Object> entry = new MyEntry <String, Object>(key, value);
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
}
}
attempt 2
public class readstringastext {
public static HashMap<String, String> map = new HashMap<String, String>();
public static void weightLimit() {
String weightLimit = "";
System.out.println(weightLimit);
// this is to see if the weightLimit is there which it isnt'.
}
public static void main(String[] args){
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
String weightLimit = "";
boolean first = true;
while ((line = bufferedReader.readLine()) != null) {
if (first) {
weightLimit = line;
first = false;
} else {
String[] values = line.split(" ");
map.put(values[0], values[1]);
}
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I see your code and and I see you read two times the file with Files.readAllLines() and standard method. So I suggest you this solution but you can use Files.readAllLines() too.
public class Main {
public static HashMap<String, String> map = new HashMap<String, String>();
private static String weightLimit = "";
public static void main(String[] args){
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
boolean first = true;
while ((line = bufferedReader.readLine()) != null) {
if (first) {
weightLimit = line;
first = false;
} else {
String[] values = line.split(" ");
map.put(values[0], values[1]);
}
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
weightLimit();
}
public static void weightLimit() {
System.out.println(weightLimit);
}
}
I believe you want to pass in the weight/value pair into a map data structure, I modified your code a little below to enable this:
public static void main(String[] args) {
HashMap<String, String> map = new HashMap<String, String>();
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String weightLimit = Files.readAllLines(Paths.get("test.txt")).get(0);
int count = 0;
while ((line = bufferedReader.readLine()) != null) {
if (count != 0) { // ignore the first line
String[] splitValue = line.split(" ");
map.put(splitValue[0], splitValue[1]);
}
count++;
}
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
// for (Map.Entry<String, String> entry : map.entrySet()) {
// System.out.println(entry.getKey());
// System.out.println(entry.getValue());
// }
}
Related
I have 100 sentences of test data. I am trying to run sentiment analysis on them but no matter what input String I am using, I am only getting a positive estimation of the input string. Each sentence gets a return value of 1.0. Any idea why this might be happening? Even if I use negative example inputs from the .txt file, the result is a positive value.
public class StartSentiment
{
public static DoccatModel model = null;
public static String[] analyzedTexts = {"Good win"};
public static void main(String[] args) throws IOException {
// begin of sentiment analysis
trainModel();
for(int i=0; i<analyzedTexts.length;i++){
classifyNewText(analyzedTexts[i]);}
}
private static String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
public static void trainModel() {
MarkableFileInputStreamFactory dataIn = null;
try {
dataIn = new MarkableFileInputStreamFactory(
new File("src\\sentiment\\Results.txt"));
ObjectStream<String> lineStream = null;
lineStream = new PlainTextByLineStream(dataIn, StandardCharsets.UTF_8);
ObjectStream<DocumentSample> sampleStream = new DocumentSampleStream(lineStream);
TrainingParameters tp = new TrainingParameters();
tp.put(TrainingParameters.CUTOFF_PARAM, "1");
tp.put(TrainingParameters.ITERATIONS_PARAM, "100");
DoccatFactory df = new DoccatFactory();
model = DocumentCategorizerME.train("en", sampleStream, tp, df);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dataIn != null) {
try {
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
public static void classifyNewText(String text) throws IOException{
DocumentCategorizerME myCategorizer = new DocumentCategorizerME(model);
double[] outcomes = myCategorizer.categorize(text.split(" ") );
String category = myCategorizer.getBestCategory(outcomes);
if (category.equalsIgnoreCase("1")){
System.out.print("The text is positive");
} else {
System.out.print("The text is negative");
}
}
Hello guys here my Code
public class Main {
public static List<String> globalList;
public static void main(String[] args) {
globalList = new ArrayList<String>();
File folder = new File("\\Documents\\Folder);
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for( String t : globalList)
{
System.out.println(t);
}
}
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
globalList.add(str);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
In my folder i have a few files. Every file contains a line of information so i took every line and saved the lines to my Arraylist globalList. Now i want to compare one object in my ArrayList with the next one, is this possible?
Just like: if (firstobj == nextobj) remove it.
Edit
Sorry guys i forgot something to write....
The problem is, the line i need to delete arent completly the same, because they start with ah generated number, this number is important for those files so i cant just delete it...
So i need to compare one part of my line if its the same i need to remove it.
One example:
10133;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10134;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
So now you see the first 2 lines are almost the same except the starting number, i need to find those lines and delete them. Because of changes i cant do somthing like if(list.contains("10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX") ).
In your case if you don't want to check if the part string contains in the list every time then it will take hours if you have a hugefile instead you can use a Set which does not allow duplicates. Unique feature of set is that it does not allow duplicates so instead of taking list of string wrap the string in a custom class and then override the equals and hashcode implementation of the class so that it will not consider the the part of string until the first occurrence of semicolon in the string.
Finally found the working code..
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
public class MyString
{
public static Set<MyString> globalSet;
private String line;
public String getLine(){
return this.line;
}
public void setLine(String newLine){
this.line = newLine;
}
public static void main(String[] args) {
File folder = new File("C:\\Users\\hbm5cf7\\Documents\\NewF");
globalSet = new HashSet<MyString>();
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(MyString t : globalSet)
{
System.out.println(t.getLine());
}
}
public static void dosomething(File file)
{
try {
BufferedReader in = new BufferedReader(new FileReader(file));
MyString str;
String line;
while ((line = in.readLine()) != null) {
str = new MyString();
str.setLine(line);
globalSet.add(str);
}
in.close();
}catch(IOException e)
{
System.out.println(e);
}
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((line == null) ? 0 : line.split(";", 2)[1].hashCode());
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (getClass() != obj.getClass())
{
return false;
}
if (this.line.equals(((MyString) obj).getLine()))
{
return true;
}
String splitString = ((MyString) obj).getLine().split(";", 2)[1];
if(this.line.endsWith(splitString))
{
return true;
}
return false;
}
}
by overriding the equals and hashcode methods you can decide which one is duplicate and which is not depending upon your requirement
Yes, it's possible. You can use equals method to compare the lines. However, you should rather compare the lines while reading the files and not store the file content in a list and compare. E.g.:
try(BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));){
String line1 = reader1.readLine();
String line2 = reader2.readLine();
if(line1 != null && line1.equals(line2)){
//Do something
}
}catch(Exception e){
//Exception handling
}
I think you're simply trying to ensure that you end up with a single list containing every 'unique' line from every file.
If this is the case you could use an implementation of Set (https://docs.oracle.com/javase/7/docs/api/java/util/Set.html) in place of your globaList such as HashSet https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
The set implementation will ensure that no duplicates are added.
I think you are looking for something like this
Iterator<String> iterator = globalList.iterator();
String lastObj = null;
String nextObj = null;
while (iterator.hasNext()){
nextObj = iterator.next();
if(lastObj == null ){
lastObj = nextObj;
}
else {
if(lastObj.equals(nextObj)){
iterator.remove();
}
}
}
EDIT:
If you have the same generated number followed by an escape character like semicolon you can get the index of the first semicolon and get the substring that start from the next character:
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
globalList.add(str);
String subString = str.substring(str.indexOf(";") + 1, str.length());
for(Iterator<String> iter = globalList.iterator(); iter.hasNext();)
{
String elem = (String) iter.next();
if(elem.contains(subString))
iter.remove();
}
}
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
Another version:
public static void dosomething(File file) {
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
// remove spaces from beginning and end of the input string
str = str.trim();
String subString = str.substring(str.indexOf(";") + 1, str.length());
boolean match = false;
// search in globalList for a match
for(String elem : globalList)
{
if(elem.contains(subString)){
match = true;
break;
}
}
// if it doesn't contain the string add it
if(!match)
globalList.add(str);
}
in.close();
} catch (IOException e) {
System.out.println(e);
}
}
#Harish Barma
Files Content:
File1:
2;XXXX;XXXX;;P;XX;XXX;1N410;20170719;1;;;0;0;1;999;1;1;;
10000;1;XXXX 096;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
10001;2;XXXX 097;1410;Autotour 1N410;10;0;K;0;;;0;2;;XXXX
10002;3;XXXX 098;1410;Autotour 1N410;13;0;K;0;;;0;2;;XXXX
10003;4;XXXX 099;1410;Autotour 1N410;19;0;K;0;;;0;2;;XXXX
10004;5;XXXX 100;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
File2:
2;XXXX;XXXX;;P;XX;XXXX;3A680;20170726;1;;;0;0;1;999;1;1;;
10082;1;XXX S146;3680;Autotour 3A680;5;0;K;0;;;0;2;;XXXx
10083;2;XXX S147;3680;Autotour 3A680;8;0;K;0;;;0;2;;XXXX
10084;3;XXX 095;3680;Autotour 3A680;6;0;K;0;;;0;2;3;XXXX
File3:
2;XXXX;XXXX;;P;XX;XXX;4M100;20170719;1;;;0;0;1;999;1;1;;
10129;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10130;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10131;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10132;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10133;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10134;1;XXXX 110;4100;Autotour 4M100;30;0;K;0;;;0;2;3;XXXX
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
(File 5-100 can cointain same lines like file 3 or different lines like file 1 or 2.)
Code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
public class MyString
{
public static Set<MyString> globalSet;
private String line;
public String getLine(){
return this.line;
}
public void setLine(String newLine){
this.line = newLine;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (getClass() != obj.getClass())
{
return false;
}
if (this.line.equals(((MyString) obj).getLine())) //compiler said i need to do this so...
{
return true;
}
String splitString = ((MyString) obj).getLine().split(";", 2)[1]; //compiler said i need to do this so...
if(this.line.endsWith(splitString))
{
return true;
}
return false;
}
public static void main(String[] args) {
File folder = new File("C:\\Users\\V90xxxxPCN\\Documents\\Neuer Ordner");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(MyString t : globalSet)
{
System.out.println(t.getLine());
}
}
public static void dosomething(File file)
{
try {
globalSet = new HashSet<MyString>();
BufferedReader in = new BufferedReader(new FileReader(file));
MyString str = new MyString();
String line;
while ((line = in.readLine()) != null) {
str.setLine(line);
globalSet.add(str);
}
}catch(IOException e)
{
System.out.println(e);
}
}
}
Expected Output:
2;XXXX;XXXX;;P;XX;XXX;1N410;20170719;1;;;0;0;1;999;1;1;;
10000;1;XXXX 096;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
10001;2;XXXX 097;1410;Autotour 1N410;10;0;K;0;;;0;2;;XXXX
10002;3;XXXX 098;1410;Autotour 1N410;13;0;K;0;;;0;2;;XXXX
10003;4;XXXX 099;1410;Autotour 1N410;19;0;K;0;;;0;2;;XXXX
10004;5;XXXX 100;1410;Autotour 1N410;15;0;K;0;;;0;2;;XXXX
2;XXXX;XXXX;;P;XX;XXXX;3A680;20170726;1;;;0;0;1;999;1;1;;
10082;1;XXX S146;3680;Autotour 3A680;5;0;K;0;;;0;2;;XXXx
10083;2;XXX S147;3680;Autotour 3A680;8;0;K;0;;;0;2;;XXXX
10084;3;XXX 095;3680;Autotour 3A680;6;0;K;0;;;0;2;3;XXXX
2;XXXX;XXXX;;P;XX;XXX;4M100;20170719;1;;;0;0;1;999;1;1;;
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
Output:
10135;1;XXXX 110;4100;Autotour 4M100;15;0;K;0;;;0;2;3;XXXX
I have written a Java code which I need to be written in Map Reduce.
I am relatively new to Map Reduce concepts.
As an input, I have a file containing multiple columns which are Pipe delimited.
Based on certain criteria which are given in my if condition of my code, I need to link the Row-Id's from the file.
for Example:
rowid|rollno|sbjctcode|subjct|dt_of_exam......|marks
2|1000|0101|PHY|02072015......|-060
9|1000|0101|PHY|02072015......|060
Desired Output:
2[9]
so that, I can get to know where is the error in the file, or for a case multiple entries etc.
Here's my Java Code:
import java.io.*;
import java.util.*;
public class MRCode {
public static void main(String[] args) {
BufferedReader in = null;
BufferedWriter out = null;
String in_line;
String PrevRollNo = "150";
ArrayList<Transaction> PCMList = new ArrayList<Transaction>();
ArrayList<Transaction> AdditionalList = new ArrayList<Transaction>();
ArrayList<Transaction> OtherList = new ArrayList<Transaction>();
try {
in = new BufferedReader(new FileReader(
"C:\\Users\\Desktop\\data.txt"));
File out_file = new File("C:\\Users\\Desktop\\op.txt");
if (!out_file.exists()) {
out_file.createNewFile();
}
FileWriter fw = new FileWriter(out_file);
out = new BufferedWriter(fw);
while ((in_line = in.readLine()) != null) {
Transaction transact = new Transaction(in_line);
if (transact.rollNo.equals(PrevRollNo)) {
if (transact.subjctCode.equals("PHY")
|| transact.subjctCode.equals("CHEM")
|| transact.subjctCode.equals("MATH")
&& transact.dt_of_exam == PrevDate) {
PCMList.add(transact);
break;
} else {
OtherList.add(transact);
}
if (transact.subjctCode.equals("0101")) {
Iterator<Transaction> pcm;
pcm = PCMList.iterator();
while (pcm.hasNext()) {
Transaction pcmtxn = pcm.next();
if (pcmtxn.subjctCode.equals("0102")
&& pcmtxn.dt_of_exam == transact.dt_of_exam
&& pcmtxn.subjct.equals(transact.subjct)
&& pcmtxn.marks == Math.abs(transact.marks)) {
pcmtxn.tgtfound = true;
transact.srcfound = true;
System.out.println(pcmtxn.row_id + "["
+ transact.row_id + "]");
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class Transaction {
public String rollNo, subjctCode, subjct, l1, l2;
public int row_id, dt_of_exam, dt_of_chking;
public double marks;
public boolean srcfound, tgtfound;
public Transaction(String in_line) {
String[] SplitData = in_line.split("\\|");
row_id = Integer.parseInt(SplitData[0]);
rollNo = SplitData[1];
subjctCode = SplitData[4];
subjct = SplitData[5];
l1 = SplitData[7];
l2 = SplitData[8];
dt_of_exam = Integer.parseInt(SplitData[2]);
dt_of_chking = Integer.parseInt(SplitData[3]);
marks = Double.parseDouble(SplitData[11]);
srcfound = false;
tgtfound = false;
}
}
}
Please help me with your thoughts on how can use Array List in my mapper class.
or how can I write this code better in Map Reduce.
Note: This is just a snapshot.
Do share your views.
I am trying to do external merge sort. Method: opening all the files in the folder 'output' and getting 1st line and sorting it, and writing it in the 'final' file and then getting the 2nd line of that file and repeating. I get an StackOverflowError. Here my file size is greater then memory.
public class mergefile6 {
public static ArrayList<String> al = new ArrayList<String>();
static HashMap hm = new HashMap();
public static String line;
public static String[][] filepoint = new String[100][2];
public static int fileline=1;
public static int i=0;
public static void main(String[] args) throws Exception{
fileread();
}
public static void fileread() throws Exception{
FileReader fileReader = null;
BufferedReader bufferedReader = null;
try {
File folder = new File("./output/");
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
int lineCount = 0;
while ((line = bufferedReader.readLine())!=null) {
lineCount++;
if (1 == lineCount) {
hm.put(line,file);
al.add(line);
filepoint[i][0]=file.toString();
filepoint[i][1]=Integer.toString(fileline);
++i;
}
}
}
}
if (null != fileReader){
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bufferedReader){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Sorting(al);
test(al);
} catch (Exception e) {
} finally {
}
}
public static void Sorting(ArrayList<String> al)throws Exception{
int length = al.size();
ArrayList<String> tmp = new ArrayList<String>(al);
mergeSort(al, tmp, 0, al.size() - 1);
}
private static void mergeSort(ArrayList<String> al, ArrayList<String> tmp, int left, int right){
//sort code
}
public static void test(ArrayList<String> al) throws Exception{
BufferedWriter bw = null;
FileWriter fw = null;
fw = new FileWriter("final",true);
bw = new BufferedWriter(fw);
bw.write(al.get(0)+" \n");
//bw.flush();
bw.close();
fw.close();
String filename = hm.get(al.get(0)).toString();
hm.remove(al.get(0));
al.remove(0);
fileforward(filename,al);
}
public static void fileforward(String filename,ArrayList<String> al) throws Exception{
long list;
FileReader fr = null;
BufferedReader br = null;
fr = new FileReader(filename);
br = new BufferedReader(fr);
for(int j=0;j<i;++j){
if(filepoint[j][0] == filename){
fileline = Integer.parseInt(filepoint[j][1]);
list = br.skip(99*fileline);
if((line = br.readLine())!=null){
hm.put(line,filename);
al.add(line);
++fileline;
filepoint[j][1]=Integer.toString(fileline);
br.close(); fr.close();
}else{}
}
}
if(al.size()==3){
Sorting(al);
test(al); }
}
}
What may be causing this error to come?
It might be an overflow caused by the mutual calls between fileforward() and test(). I don't know try debugging the ArrayList's size with logs or prints. If it's always equal to 3 that's the problem.
I'm working on a homework assignment and have run into an odd "ArrayOutOfBoundsException" error - I know what the error means (essentially I'm trying to reference a location in an array that isn't there) but I'm not sure why it's throwing that error? I'm not sure what I'm missing, but obviously there must be some logic error somewhere that I'm not seeing.
PhoneDirectory.java
import java.util.HashMap;
import java.io.*;
class PhoneDirectory {
private HashMap<String, String> directoryMap;
File directory;
public PhoneDirectory() { //create file for phone-directory
directory = new File("phone-directory.txt");
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public PhoneDirectory(String phoneDirectoryFile) {
directory = new File(phoneDirectoryFile);
directoryMap = new HashMap<String, String>();
try(BufferedReader buffer = new BufferedReader(new FileReader(directory))) {
String currentLine;
while((currentLine = buffer.readLine()) != null) { //set currentLine = buffer.readLine() and check if not null
String[] fileData = currentLine.split(","); //create array of values in text file - split by comma
directoryMap.put(fileData[0], fileData[1]); //add item to directoryMap
}
}
catch(IOException err) {
err.printStackTrace();
}
}
public String Lookup(String personName) {
if(directoryMap.containsKey(personName))
return directoryMap.get(personName);
else
return "This person is not in the directory.";
}
public void AddOrChangeEntry(String name, String phoneNumber) {
//ASK IF "IF-ELSE" CHECK IS NECESSARY
if(directoryMap.containsKey(name))
directoryMap.put(name,phoneNumber); //if name is a key, update listing
else
directoryMap.put(name, phoneNumber); //otherwise - create new entry with name
}
public void DeleteEntry(String name) {
if(directoryMap.containsKey(name))
directoryMap.remove(name);
else
System.out.println("The person you are looking for is not in this directory.");
}
public void Write() {
try(BufferedWriter writeDestination = new BufferedWriter(new FileWriter(directory)))
{
for(String key : directoryMap.keySet())
{
writeDestination.write(key + ", " + directoryMap.get(key) + '\n');
writeDestination.newLine();
}
}
catch(IOException err) {
err.printStackTrace();
}
}
}
Driver.java
public class Driver {
PhoneDirectory list1;
public static void main(String[] args) {
PhoneDirectory list1 = new PhoneDirectory("test.txt");
list1.AddOrChangeEntry("Disney World","123-456-7890");
list1.Write();
}
}
Essentially I'm creating a file called "test.txt" and adding the line "Disney World, 123-456-7890" - what's weird is that the code still works - but it throws me that error anyway, so what's really happening? (For the record, I'm referring to the line(s): directoryMap.put(fileData[0], fileData[1]) - which would be line 14 and 28 respectively.)