0

I'm trying to make a program that checks to see if a string of letters is a text file, for a dictionary type program, but I can't get it to work. My code is:

package main;

import java.io.*;
import java.util.Scanner;

public class Test {
public static void main(String [] args) {
    Scanner Enter = new Scanner(System.in);


    System.out.println("Please Enter your word");
    String Guess = Enter.next();

    // The name of the file to open.
    String fileName = "../Dictionary/Resources/wordsA.txt";

    // This will reference one line at a time
    String line = null;

    int i = 0;
    int numWords = 0;

    String[] wordArray;
    wordArray = new String[15000];


    try {
        // FileReader reads text files in the default encoding.
        FileReader fileReader = 
            new FileReader(fileName);

        // Always wrap FileReader in BufferedReader.
        BufferedReader bufferedReader = 
            new BufferedReader(fileReader);

        while((line = bufferedReader.readLine()) != null) {
            numWords++;

            wordArray[numWords] = line;
        }

        // Always close files.
        bufferedReader.close();         
    }
    catch(FileNotFoundException ex) {
        System.out.println(
            "Unable to open file '" + 
            fileName + "'");                
    }
    catch(IOException ex) {
        System.out.println(
            "Error reading file '" 
            + fileName + "'");                  
        // Or we could just do this: 
        // ex.printStackTrace();
    }
    for(i = 0; i < 10; i++){
        System.out.println(wordArray[i]);
        if(Guess == wordArray[i]){
            System.out.println("In dictionary");
        }
        else{
            System.out.println("Not in Dictionary");
        }
    }
}
}

It runs through my text file and prints the first 10 words in the file and displays whether or not my word given is in the text file dictionary or not. What I don't get is as you can see from my output below, I enter a word like "AA" and it still says not in the dictionary but it should say it is? I can't figure out why.

Example Output:

Please Enter your word
AA
null
Not in Dictionary
AA
Not in Dictionary
AAH
Not in Dictionary
AAHED
Not in Dictionary
AAHING
Not in Dictionary
AAHS
Not in Dictionary
AAL
Not in Dictionary
AALII
Not in Dictionary
AALIIS
Not in Dictionary
AALS
Not in Dictionary
Kevin
  • 53
  • 2
  • 8
  • Use `if (Guess.equals(wordArray[i]))` ... `==` is for comparing references, not the strings themselves – Tim Biegeleisen Feb 20 '17 at 00:54
  • Trying Guess.equalsIgnoreCase( wordArray[i] ), might help your problems since case-sensitivity is an issue worth noticing when comparing strings, plus **Guess == wordArray[i]** is certainly not the way of comparing characters within String, since you are talking strictly Java and not C++ – ShayHaned Feb 20 '17 at 00:54
  • Yes, that fixed it. Thank you guys so much. – Kevin Feb 20 '17 at 01:10

0 Answers0