I want to make a word search java program where whenever I enter a word that contains wild cards for example: b*t
I want to find all the possible words that fit that word from a text file that I have.
This is what I have done so far,
Scanner cin = new Scanner(System.in);
System.out.print("Enter a query: ");
String input = cin.nextLine();
try{
String line;
BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
while((line = br.readLine()) != null){
if (input.length()==line.length()) {//show all letters in that range
if ('*' != input.charAt(x)) {//check if letters contain '*'
if (line.charAt(x) == input.charAt(x)) {//check if letters match
System.out.print(line+"\n");//show all words that fit criteria
}else{//skip letter
x=+1;
}
}else{//skip
x=+1;
}
}// end if
}// end while
}catch (IOException e){
e.printStackTrace();
}
I can find all the words of certain length, I'm just struggling on finding the words that fit my query.
I believe that this fit your needs:
public static void main(String[] args) {
Scanner cin = new Scanner(System.in);
System.out.print("Enter a query: ");
String input = cin.nextLine();
try{
String line;
BufferedReader br = new BufferedReader(new FileReader("dictionary.txt"));
while((line = br.readLine()) != null){
String[] words = line.split(" ");
for(String w: words) {
String p = "^" + input.replaceAll("\\*", ".*") + "$";
if (w.matches(p)) {
System.out.println(w);
}
}
}
}catch (IOException e){
e.printStackTrace();
}
System.exit(0);
}
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.