我正在尝试编写一个包含两个单词或短语的程序,并通过查看它们的 unicode 值是否匹配来测试它们是否是字谜。只有当它们的长度相同时,“搜索”方法才会运行。我遇到了问题,但现在已经解决了。
这是修改后的版本:
我想知道您对代码布局方式的看法。清楚吗?我应该采取不同的做法吗?或者你觉得它很容易阅读?你对我如何让别人更清楚有什么建议吗?
如果我添加评论,它们应该简短还是我应该在多行评论中解释该部分是如何工作的?
我想让它看起来尽可能直截了当,对此我几乎没有得到真正的建议。所以如果有人有任何想法。
import java.util.Scanner;
public class AnagramCount {
public static void main(String[] args) {
System.out.println("Please enter two words, one per line, to test if it is an anagram");
Scanner userInput = new Scanner(System.in);
String word1 = userInput.nextLine();
String word2 = userInput.nextLine();
int count = 0;
int[] char_code = new int[word1.length()];
int[] char_code2 = new int[word2.length()];
char[] temp = word2.toCharArray();
boolean match = true;
if (word1.length() == word2.length()){
search(word1, word2, count, char_code, char_code2, match, temp);
if (match == true){
if (char_code[word1.length()-1] == 0){
match = false;
}
else {
// if match remains true after this final check, information about it will print
System.out.print("word1 unicode values: ");
for(int i = 0; i < word1.length(); i++){
System.out.print(char_code[i] + " ");
}
System.out.println();
System.out.print("word2 unicode values: ");
for(int i = 0; i < word1.length(); i++){
System.out.print(char_code2[i] + " ");
}
}
}
}
else {
match = false;
}
System.out.println("\n" + "Anagram? t/f?: " + match);
}
public static void search(String word1, String word2, int count, int[] char_code, int[] char_code2, boolean match, char[] temp)
{
StringBuilder word1check = new StringBuilder(word1);
StringBuilder word2check = new StringBuilder(word2);
int word1_unicode = 0;
int word2_unicode = 0;
if(count >= word1.length())
return;
else
{
for(int i = 0; i < word2.length(); i++){
if (word1.charAt(count) == word2.charAt(i)){
word1_unicode = word1check.codePointAt(count);
char_code[count] = word1_unicode;
temp[i] = 0;
String str = new String(temp);
word2 = str;
word2_unicode = word2check.codePointAt(i);
char_code2[count] = word2_unicode;
if(count==word1.length()-1)
break;
search(word1, word2, ++count, char_code, char_code2, match, temp);
}
}
}
return;
}
}