Java Spelling Check

Sheeraz Gul Oct 12, 2023
Java Spelling Check

This tutorial demonstrates how to check word spelling in Java.

Java Spelling Check

Many libraries can check a word’s spelling using their English dictionary. These libraries can be used if you don’t want to create your dictionary to check the spelling of English words.

But if you have a file for a dictionary and you want to use it to check the spelling of words using that dictionary, then we can use Java code to create our spell checker. Follow the steps below to create our spell checker.

  • First, create a HashSet of your dictionary file.
  • Create a scanner to take the input from the user. The input will be a sentence.
  • Split the sentence into words and put them into an array.
  • Use the for loop to check each word from the dictionary file.
  • If the file contains the word, it will be correct; if it doesn’t, it will be incorrect.

Let’s try to implement an example based on the above steps. We downloaded our dictionary file with more than 84,000 words from here; see the example.

package delftstack;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Example {
  public static void main(String[] args) throws Exception {
    Set<String> Demo_Dictionary = new HashSet<>(Files.readAllLines(Paths.get("dictionary.txt")));
    Scanner Demo_Input = new Scanner(System.in);
    System.out.println("Type a sentence to check the spelling/correct words :)");
    String Demo_Sentence = Demo_Input.nextLine();
    String[] Sentence_Words = Demo_Sentence.split(" ");
    for (String Word : Sentence_Words)
      if (Demo_Dictionary.contains(Word))
        System.out.println(Word + " : correct");
      else
        System.out.println(Word + " : incorrect");
  }
}

Let’s try to check the spelling of a sentence from the given dictionary. See output:

Type a sentence to check the spelling/correct words :)
hello this is delftstack the best tutorial site
hello : correct
this : correct
is : correct
delftstack : incorrect
the : correct
best : correct
tutorial : correct
site : correct

From the above sentence, the dictionary doesn’t contain the word delftstack, which is why it is incorrect, and if you want to add it to the dictionary, add the word at the end of the dictionary.txt file.

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook