tags:

views:

57

answers:

4

Hello, 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);
      }

    }
+1  A: 

Make sure that the file lies in the same directory as your .class file. It doesn't matter if it is in the same as your .java file or not.

Other than that, the only problem I can see is in your indentation, which doesn't matter.

Serplat
A: 

Put the anagrams.in file in the same location as the .class file. Then you will be able to read the file. And this should help you get some links on how to read from files in Java.

Gangadhar
+1  A: 

A few tips:

  1. Abide to proper code indentation
    • If you're using an IDE like Eclipse, it can automatically correct indentation for you
  2. Develop debugging instinct
    • Try to get what the current working directory is, and list all the files in it
  3. Refactor repetitive code
    • Writing paired statements like you did should immediately raise red flags
  4. Effective Java 2nd Edition
    • Item 23: Don't use raw types in new code
    • Item 52: Refer to objects by their interfaces
    • Item 46: Prefer for-each loops to traditional for loops
  5. Use sensible variable names

With regards to 2, try something like this:

public static void listDir() {
    File current = new File(".");
    System.out.println(current.getAbsolutePath());
    for (String filename : current.list()) {
        System.out.println(filename);
    }
}

Then in your main, simply call listDir before 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:

static Set<Character> usedCharactersIn(String s) {
    Set<Character> set = new HashSet<Character>();
    for (char ch : s.toLowerCase().toCharArray()) {
        set.add(ch);
    }
    return set;
}

Note how Set<E> is used instead of Map<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:

    String s1 = ...;
    String s2 = ...;

    boolean isNotQuiteAnagram = (s1.length() == s2.length()) &&
        usedCharactersIn(s1).containsAll(usedCharactersIn(s2));

Note how variables are now named rather sensibly, highlighting their roles. Note also that this logic does not quite determine that s1 is an anagram of s2 (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

polygenelubricants
Thanks this helped, but about i indenting, I prefer doing it my way, its just easier to read, because it look more logical and coherent.
Zerobu
@Zerobu: If you keep your code private, go ahead. But when you'd like to publish your source and/or do a Java job in a team and so on, then you'd really like to adhere the [Java Coding Conventions](http://www.oracle.com/technetwork/java/codeconvtoc-136057.html). Not only for yourself, but also for others, now and in the future.
BalusC
@Zerobu: Alright, pick a style and stick to it, but don't do what you are doing in your question; in a number of places you are suddenly indenting less without a reason, that just makes the code messy and it is coherent by no standard.
Jasper
@BalusC: Just wondering, is writing Allman-style Java frowned upon?
Jasper
BalusC
@BalusC: That's a yes, I suppose? My experience with Java may be limited to instances where I was allowed to choose my own indentation patterns, my C# experience is non-existent, so a comparison between the two is not going to make it any clearer for me.
Jasper
+1  A: 

The normal practice is to put resources in the runtime classpath or to add its path to the runtime classpath so that you can get it by the classloader. Using relative paths in Java IO is considered poor practice since it breaks portability. The relative path would be dependent on the current working directory over which you have totally no control from inside the Java code.

After having placed it in the classpath (assuming that it's in the same folder as the Java class itself), just do so:

BufferedReader reader = null;

try {
    InputStream input = Practice.class.getResourceAsStream("anagrams.in");
    reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); // Or whatever encoding it is in.

    // Process it.
    // ...
} finally {
    if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}

Closing in finally is by the way mandatory to release the lock on the file after reading.

BalusC