다음은 문제 문입니다. 두 문자열이 같은 문자를 포함하는지에 따라 true 또는 false를 반환하는 2 문자열을 비교하는 함수를 작성하십시오. 명령은 중요하지 않습니다.Java 초급, 중첩 for 루프의 문자열 비교
내 중첩 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...");
}
}
항상 루프를 통해 처음에는 '중단'됩니다.'if'에서'break'를 제거하고'else'에서 남겨 둡니다. – resueman
왜'char [] word1b = word1.toCharArray();'가 아닌가? (또는'word1.charAt (i)'와'word2.charAt (j)'를 비교하면 새로운 배열 생성을 피할 수 있습니다). –
각'String '의 문자를'Set'에 넣습니다. 그런 다음 세트를 비교하십시오. –