我一直在尝试在此处和此处进行一些代码调整,以使输出正确。我试图让我的代码能够重新排列单词中的字母,以使https://github.com/dwyl/english-words中的word.txt中存在其他单词。任何帮助,将不胜感激。谢谢。
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/Test.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
StringBuilder b = new StringBuilder();
String c = r.readLine();
while (c != null) {
b.append(c);
b.append(" ");
c = r.readLine();
}
Scanner s = new Scanner(System.in);
String in = s.nextLine();
char[] input = new char[in.length()];
for (int i = 0; i < input.length; i++) {
input[i] = in.charAt(i);
}
char[] temp = null;
for (int i = 0; i < b.length(); i++) {
if (i < b.length() - 1 && b.charAt(i) == ' ' && b.charAt(i + 1) != ' ') {
boolean found = false;
int counter = 0;
while (!found) {
counter++;
if (b.charAt(i + counter) == ' ') {
found = true;
temp = new char[counter - 1];
for (int j = i + 1; j < i + counter; j++) {
temp[j] = b.charAt(j);
}
}
}
}
}
if (Arrays.asList(input).contains(temp)) {
System.out.println(temp);
}
}
}
这是我经过调整的代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class WordsInWords {
public static void main(String[] args) throws IOException {
String file = "/Users/laptop/Desktop/words.txt";
BufferedReader r = new BufferedReader(new FileReader(file));
String[] words;
String c = r.readLine();
int a=0;
while (c != null) {
c = r.readLine();
a++;
}
words=new String[a];
a=0;
r = new BufferedReader(new FileReader(file));
String temp=r.readLine();
while (temp != null) {
words[a]=r.readLine();
temp=words[a];
a++;
}
for (int i = 0; i < words.length; i++) {
System.out.println(words[i]);
}
Scanner s = new Scanner(System.in);
String input = s.nextLine();
List<String> found = findRearranged(input,words);
System.out.println("For '" + input + "' found: " + Arrays.toString(found.toArray()));
}
public static List<String> findRearranged(String input,String[] words) {
List<String> found = new ArrayList<>();
for (String w : words) {
if (hasSameLetters(w,input)) {
found.add(w);
}
}
return found;
}
public static boolean hasSameLetters(String a,String b) {
if (a.length() != b.length()) {
return false;
}
while (a.length() > 0) {
for (char c : b.toCharArray()) {
int index = a.indexOf(c);
if (index >= 0) {
a = a.replace(String.valueOf(c),"");
} else {
return false;
}
}
}
return true;
}
}