This is web exercise 3.1.45. from the book Computer Science An Interdisciplinary Approach by Sedgewick & Wayne:
Write a program that reads in a list of words from the command line and prints
true
if they form a word chain andfalse
otherwise. In a word chain, adjacent words must differ in exactly one letter, e.g., HEAL, HEAD, DEAD, DEED, DEER, BEER.
Here is my program:
public class WordChainChecker
{
public static boolean checkWordCouple(String word1, String word2)
{
int counter = 0;
int wordLength = word1.length();
for (int i = 0; i < wordLength; i++)
{
if (word1.charAt(i) != word2.charAt(i)) counter++;
}
if (counter > 1) return false;
else return true;
}
public static void main(String[] args)
{
String word1 = StdIn.readString();
String word2 = StdIn.readString();
boolean truth = true && checkWordCouple(word1,word2);
while (!StdIn.isEmpty())
{
word1 = StdIn.readString();
truth = truth && checkWordCouple(word1,word2);
word2 = word1;
}
System.out.println(truth);
}
}
StdIn is a simple API written by the authors of the book. I checked my program and it works.
Is there any way that I can improve my program?
Thanks for your attention.