1

I am trying to see if a string in my array matches a word. If so, perform the If statement.

Sounds simple as pie but the If statement does not see the string from the array!

The array (temps) contains nothing but "non"s so I know it's something wrong with the If statment.

Here is the snippet of code:

    if ("non".equals(temps.get(3))) {
        System.out.println("Don't know.");
    }

Where temps is the array containing "non"s on different lines.

Here is the full code in case anyone is wondering:

public class Dump {

    public static void main(String[] args) throws IOException {
    String token1 = "";

    //Reads in presidentsUSA.txt.
    Scanner inFile1 = new Scanner(new File("presidentsUSA.txt"));

    //Splits .txt file via new lines.
    inFile1.useDelimiter("\\n");

    List<String> temps = new ArrayList<String>();

    while (inFile1.hasNext()) {
      token1 = inFile1.next();
      temps.add(token1);
    }
    inFile1.close();

    // Stores each new line into an array called temps.
    String[] tempsArray = temps.toArray(new String[0]);

        if ("non".equals(temps.get(3))) {
            System.out.println("Don't know.");
        }

    }
}
Dezza
  • 1,094
  • 4
  • 22
  • 25
Lewie
  • 15
  • 2
  • 2
    This is a greate example where you can make yourself farmilar with the debugger. – Peter Mar 23 '16 at 13:02
  • Try printing out temps.get(3) and temps.get(3).length(). You might find it is not exactly what you want. Using temps.get(3).startsWith("non") might fix it. – BPS Mar 23 '16 at 13:49

1 Answers1

0

The most probable explanation why your if statement returns false is that you are on a Windows OS.

If you debug your code and watch temps.get(3) it will show the content as

non\r

and non\r does not equal non

Solution:

inFile1.useDelimiter("\\r\\n");

Check the accepted answere here (especially point 4): Difference between \n and \r?

Community
  • 1
  • 1
Moh-Aw
  • 2,976
  • 2
  • 30
  • 44