0

EDIT: Problem solved! I was just blind :)

As the title says, I've been working on finding the distance between two inputted words. The dictionary file is just a file with words separated by a space. Every time that I run the program, it says that I have 0 words between the two inputted. I'm not sure what I am doing wrong.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class wordDistance {

    public static void main(String[] args) throws FileNotFoundException {

        Scanner s = new Scanner(System.in);
        Scanner sfile = new Scanner(new File("C:/Users/name/Desktop/Eclipse/APCS/src/dictionary.txt"));

        int count = 0;

        System.out.print("Type two words: ");
        String start = s.next();
        String end = s.next();

        while (sfile.hasNextLine()) {

            String line = sfile.nextLine();
            String[] words = line.split(" ");

            for (int i = 0; i < words.length; i++) {
                if (words[i] == start) {
                    for (int j = i + 1; j < words.length; j++) {
                        if (!(words[j] == end)) {
                            count++;
                        }
                        if (words[j] == end) {
                            break;
                        }
                    }
                }
            }
        }
        System.out.println("There are " + count + " words between " + start + " and " + end);
    }
}
SnazZ
  • 3
  • 4
  • Possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Jeffrey Bosboom Mar 11 '16 at 06:06

3 Answers3

0

the == operator checks whether the references to the objects are equal, use the method String.equals(String); instead.

For example:

  • if (words[j].equals(end))
  • if (!(words[j].equals(end)))
  • if (words[i].equals(start))
Community
  • 1
  • 1
Alex Weitz
  • 3,199
  • 4
  • 34
  • 57
0

you should compare strings with equals() rather than ==

For example,

if (words[j].equals(end)) {
    break;
}

if you change your comparisons you should get the correct output.

mikefaheysd
  • 126
  • 4
0

You cannot use the == operator to equate strings. Use the equals(String string) function instead.

if (!words[j].equals(end)) {
   count++;
}
if (words[j].equals(end)) {
   break;
}