【发布时间】:2023-03-25 04:35:02
【问题描述】:
这里是问题陈述:编写一个函数,比较两个字符串以根据两个字符串是否包含相同的字母来返回真或假。顺序无关紧要。
我不知道如何正确比较嵌套 for 循环中的字符数组。我希望我能更具体地说明我的问题是什么,但我是一个真正的新手,不明白为什么这不起作用。我确实相信它没有在嵌套的 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...");
}
}
【问题讨论】:
-
你总是
break第一次通过循环。删除if中的break并保留else中的那个。 -
为什么不只是
char[] word1b = word1.toCharArray();? (或者,比较word1.charAt(i)和word2.charAt(j),这样可以避免创建新数组)。 -
将每个
String的字符放入一个Set。然后比较集合。 -
@AndyTurner,这并不是我提到的问题的重复。这是一个新手级别的问题,但不是关于
==与equals()。我的错。 -
另外,请注意您正在检查
word1中的所有字母是否都在word2中;并非word2中的所有字母都在word1中。