以下是问题陈述:编写一个比较2个字符串的函数,根据两个字符串是否包含相同的字母,返回true或false。顺序无关紧要。Java初学者,比较嵌套循环中的字符串
我不知道如何正确比较我的嵌套循环中的字符数组。我希望我可以更具体地了解我的问题,但我是一个非常新的学习者,不知道为什么这不起作用。我相信它没有在嵌套for循环中做我想要的。提前致谢!
import java.util.Scanner;
public class PracticeProblems {
public static boolean stringCompare(String word1, String word2) {
char[] word1b = new char[word1.length()];
char[] word2b = new char[word2.length()];
boolean compareBool = false;
for(int i = 0; i < word1.length(); i++) {
word1b[i] = word1.charAt(i);
word2b[i] = word2.charAt(i);
}
for(int i = 0; i < word1.length(); i++) {
for(int j = 0; j < word2.length(); j++) {
if(word1b[i] == word2b[j]) {
compareBool = true;
break;
} else {
compareBool = false;
break;
}
}
}
return compareBool;
}
public static void main(String []args) {
Scanner scan = new Scanner(System.in);
System.out.println("Word 1?");
String word1 = scan.nextLine();
System.out.println("Word 2?");
String word2 = scan.nextLine();
if(PracticeProblems.stringCompare(word1, word2) == true) {
System.out.println("Same Letters!");
} else {
System.out.println("Different Letters...");
}
}
你总是在第一次通过循环“休息”。删除'if'中的'break'并将其保留在'else'中。 – resueman
为什么不只是'char [] word1b = word1.toCharArray();'? (或者,比较'word1.charAt(i)'和'word2.charAt(j)',避免创建新的数组)。 –
将每个“字符串”的字符放入“集合”中。然后比较这些集合。 –