【发布时间】:2014-11-12 06:23:30
【问题描述】:
我是论坛的新手(作为注册用户),所以我非常努力(我发誓!)不发布问题,寻找旧答案,我检查了其他人在与我类似的问题中的错误,但是我什么都做不好。
我的代码,在这里,应该检查一个词是否是另一个词的字谜。我很确定我的生活变得复杂了很多,本来会有更简单的方法来做到这一点,但是......我已经为此工作了一段时间,并希望看到它起作用......
知道为什么没有吗?
我所看到的只是空字典,当两个单词具有相同数量的字母时,它们始终是字谜(这意味着实际上我的字典没有做任何事情:'()
import acm.program.ConsoleProgram;
import java.util.*;
public class Anagrams extends ConsoleProgram {
String firstWord;
String secondWord;
public boolean checkLength(String firstWord, String secondWord) {
if (firstWord.length() == secondWord.length()) {
println("Same length!");
return true;
} else {
return false;
}
}
public boolean anagram(String firstWord, String secondWord) {
firstWord = firstWord.toLowerCase();
secondWord = secondWord.toLowerCase();
String[] firstArray = firstWord.split("\\a");
String[] secondArray = secondWord.split("\\a");
int firstLength = firstWord.length();
int secondLength = secondWord.length();
Map<String, Integer> firstDictionary = new HashMap<String, Integer>();
Map<String, Integer> secondDictionary = new HashMap<String, Integer>();
for (firstLength = 0; firstLength == firstArray.length; firstLength++) {
System.out.println("checking the letter " + firstArray[firstLength] + " in array" + firstArray.toString());
if (firstDictionary.get(firstArray[firstLength]) == null) {
firstDictionary.put(firstArray[firstLength], 1);
} else {
firstDictionary.put(firstArray[firstLength], firstDictionary.get(firstArray[firstLength]) + 1);
}
}
for (secondLength = 0; secondLength == secondArray.length; secondLength++) {
if (secondDictionary.get(secondArray[secondLength]) == null) {
secondDictionary.put(secondArray[secondLength], 1);
} else {
secondDictionary.put(secondArray[secondLength], secondDictionary.get(secondArray[secondLength]) + 1);
}
}
if (firstDictionary.equals(secondDictionary)) {
return true;
} else {
return false;
}
}
public void run() {
int runAgain = 0;
while (runAgain == 0) {
println("Enter the first word to be analyzed");
firstWord = readLine();
println("Enter the second word to be analyzed");
secondWord = readLine();
if (checkLength(firstWord, secondWord) == true) {
if (anagram(firstWord, secondWord) == true) {
println("Yes! The two words are anagrams!");
}
} else {
println("No. The two words are not anagrams!");
}
}
}
}
【问题讨论】: