I am sorry if there is something very simple I am missing.
I have the following code:
import java.util.Scanner;
import java.io.File;
import java.util.regex.Pattern;
public class UnJumble
{
String[] ws;
int ind=0;
public static void main(String args[]) throws Exception
{
System.out.println("Enter a jumbled word");
String w = new Scanner(System.in).next();
UnJumble uj = new UnJumble();
uj.ws = new String[uj.fact(w.length())];
uj.makeWords("",w);
int c=1;
Scanner sc = new Scanner(new File("dict.txt"));
for(int i=0; i<uj.ws.length; i++)
{
Pattern pat = Pattern.compile(uj.ws[i].toUpperCase());
if(sc.hasNext(pat))
System.out.println(c+++" : \'"+uj.ws[i]+"\'");
}
System.out.println("Search Completed.");
if(c==1) System.out.println("No word found.");
}
public void makeWords(String p,String s)
{
if(s.length()==0)
ws[ind++] = p;
else
for(int i=0; i<s.length(); i++)
makeWords(p+s.charAt(i),s.substring(0,i)+s.substring(i+1));
}
public int fact(int n)
{
if(n==0) return 1;
else return n*fact(n-1);
}
}
The dict.txt
file is the SOWPODS dictionary, which is the official Scrabble dictionary..
I want to take in a jumbled word, and rearrange it to check if it is present in the dictionary. If it is, then print it out.
When I try tra
as input, the output says No word Found.
. But the output should have the words tar
, art
and rat
.
Please tell me where I am making a mistake. I apologize if I have made a very simple mistake, because this is the first time I am working with Pattern
.
This is from the JavaDoc of Scanner.hasNext(Pattern pattern)
(with my highlighting)
Returns true if the next complete token matches the specified pattern.
As your Scanner was initialized with file dict.txt
, it is positioned on first word .
And the first complete token in dict.txt does not match any of your scambled words, so no match is found.
Note: This assumes you have one word per line
I'd think you may want to change your code to find your scrambled text somewhere in the dictionary file (with start-of-line before and end-of-line after) resulting in a pattern "(^|\\\\W)"+uj.ws[i].toUpperCase()+"(\\\\W|$)"
and something like
String dictstring = your dictionary as one string;
Matcher m = p.matcher(dictstring);
if(m.find()) {
...
I recommend IOUtils.toString()
for reading your file like this:
String dictstring = "";
try(InputStream is = new FileInputStream("dict.txt")) {
dictstring = IOUtils.toString(is);
}
Here's a small example code to get familiar with pattern and matcher:
String dictString= "ONE\r\nTWO\r\nTHREE";
Pattern p = Pattern.compile("(^|\\W)TWO(\\W|$)");
Matcher m = p.matcher(dictString);
if(m.find()) {
System.out.println("MATCH: " + m.group());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.