Results 1 to 2 of 2
  1. #1
    dre is offline Member
    Join Date
    Jun 2009
    Rep Power

    Default Real simple code giving me trouble!


    I'd like to get this simple piece of code that reads an input files, adds each line to an arraylist and recognizes if a particular exists in a text file. If it does, print out the indexOf the string in the arraylist.

    Here's the code I THOUGHT would do it:

    public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
    List<String> s = new ArrayList<String>();
    String line;
    int n = 0;
    while ((line = r.readLine()) != null) {
    if (line == "test")



    Except when I execute the program it doesn't print anything out! I want it to print out the location of the line "test" (and it does exist in my input file) but nothing prints out and the program ends.

    I know the problem lies in the "if (line == "test")", particularily the "== "test"" part. I tested it but changing it to "if (line != null)" and the program executed perfectly.

    Any ideas as to why it's not printing out?

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Rep Power

    Default Re: Real simple code giving me trouble!

    When comparing String values for equality, use the equals method. == compares whether the references are equal, not necessarily the String value.

Similar Threads

  1. Read unicode code points from file to real characters
    By lordelf2004 in forum Advanced Java
    Replies: 1
    Last Post: 07-30-2011, 11:37 AM
  2. Replies: 37
    Last Post: 05-02-2011, 08:09 AM
  3. Having trouble with code in DrJava
    By jonstewart in forum New To Java
    Replies: 15
    Last Post: 04-07-2011, 11:34 PM
  4. Java code giving error
    By alfarida in forum New To Java
    Replies: 3
    Last Post: 11-10-2010, 07:11 PM
  5. Pls check why my code is giving a runtime error
    By Beginner in forum New To Java
    Replies: 3
    Last Post: 05-26-2010, 12:32 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts