Search code examples
javastringnetbeansequalsreadfile

equalsIgnoreCase not working (Java)


Here is one of my methods which scans the TXT file and counts the occurrence of the word "Jan" which should be 1, since the Date in the txt file is 09-Jan-2018

static int getFirstMonth() throws FileNotFoundException {
    File file_to_scan = new File("happyFile.txt");
    Scanner scannerInput = new Scanner(file_to_scan);
    int count = 0;
    while (scannerInput.hasNext()) { 
        String nextWord = scannerInput.next(); 
        if (nextWord.equalsIgnoreCase("Jan")) {
            count++;      
        }
    }
    return count;
}

Here is the txt file incase anyone wants to have a look.

If I am using nextWord.equals("Jan") I would understand why it's not picking up because it's not the full word, but shouldn't ignoreCase ignore that and pick up the 3 consecutive letters? Could anyone please help me with this problem.


Solution

  • String.equals() will compare the entire words. In this case, Scanner.next() is separating words by white space, so it's reading "09-Jan-2018" into nextWord.

    If you want to see if nextWord contains "Jan", consider using something like String.contains() and for case-insensitivity, you can convert each string to to lowercase before comparing.

    For example: if (nextWord.toLowerCase().contains("jan"))