I am trying to open this file in java and i want to know what i am doing wrong. The in file lies in the same directory as my Java file, but i tried to open this with both netbeans and eclipse and it gave a file not found exception. Can someone help me open this file and read from it. I am really new to java files. Here is the code
import java.util.*;
import java.io.*;
public class Practice
{
public static void main(String[] args)throws IOException
{
FileReader fin = new FileReader("anagrams.in");
BufferedReader br = new BufferedReader(fin);
System.out.println(fin);
String string = "Madam Curie";
String test = "Radium came";
string = string.toLowerCase();
test = test.toLowerCase();
string = string.replaceAll("[^a-zA-Z0-9]+", "");
test = test.replaceAll("[^a-zA-Z0-9]+", "");
char[] array = string.toCharArray();
char[] array2 = test.toCharArray();
boolean flag = false;
HashMap hm = new HashMap();
for(int i = 0; i < array.length; i++)
{
hm.put(array[i], array[i]);
}
for(int i = 0; i < array2.length; i++)
{
if(hm.get(array2[i]) == null || test.length() != string.length())
{
flag = false;
i = array2.length;
}
else
{
flag = true;
}
}
System.out.println(flag);
}
}
A few tips:
forloopsWith regards to 2, try something like this:
Then in your
main, simply calllistDirbefore everything else, and see if you’re running the app from the right directory, and if there’s a"anagrams.in"in the directory. Note that some platforms are case-sensitive.With regards to 3 and 4, consider having a helper method like this:
Note how
Set<E>is used instead ofMap<K,V>. Looking at the rest of the code, you didn’t seem to actually need a mapping, but rather a set of some sort (but more on that later).You can then have something like this in
main, which makes the logic very readable:Note how variables are now named rather sensibly, highlighting their roles. Note also that this logic does not quite determine that
s1is an anagram ofs2(consider e.g."abb"and"aab"), but this is in fact what you were doing.Since this looks like homework, I’ll leave it up to you to try to figure out when two strings are anagrams.
See also
Related questions