Java初学者,比较嵌套循环中的字符串



这是问题语句:编写一个函数,将2个字符串比较以返回true或false,具体取决于两个字符串是否包含相同的字母。订单没关系。

我不知道如何正确地比较嵌套循环中的字符阵列。我希望我能对我的问题更具体,但是我是一个非常新的学习者,看不出为什么这不起作用。我确实相信这不是在筑巢的循环中做我想做的事情。预先感谢!

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...");
    }
}

下面的代码将完成工作。从本质上讲,这是弗兰克评论的扩展。我们将两个字符串转换为两组,然后比较。

import java.util.*;
public class SameChars {
    // Logic to convert the string to a set
    public static Set<Character> stringToCharSet(String str) {
       Set<Character> charSet = new HashSet<Character>();
       char arrayChar[] = str.toCharArray();
       for (char aChar : arrayChar) {
          charSet.add(aChar);
       }
       return charSet;
    }
    // Compares the two sets
    public static boolean hasSameChars(String str1, String str2) {
       return stringToCharSet(str1).equals(stringToCharSet(str2));
    }
    public static void main(String args[]){
        // Should return true
        System.out.println(hasSameChars("hello", "olleh"));
        // Should returns false
        System.out.println(hasSameChars("hellox", "olleh"));
    }
}

我在比较之前对数组进行了排序。

    //import statement for Arrays class
    import java.util.Arrays;
    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 = true;
        for(int i = 0; i < word1.length(); i++) {
            word1b[i] = word1.charAt(i);
        }   
        //sort the new char array
        Arrays.sort(word1b);

        // added a second loop to for the second world
        for(int i = 0; i < word2.length(); i++) {
            word2b[i] = word2.charAt(i);
        } 
        Arrays.sort(word2b);
        for(int i = 0; i < word1.length(); i++) {
            //removed second for loop. 
    //        for(int j = 0; j < word2.length(); j++) {
            // if the two strings have different length, then they are different
            if((word1.length()!=word2.length())){
                compareBool = false;
                break;
            }
            //changed to not equal  
            if( (word1b[i] != word2b[i]) ) {
                compareBool = false;
                break;
            } 
            //removed else statment
    //      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...");
        }
        //resource leak.  use close() method.
        scan.close();
    }
    }

允许我将您的boolean变量重命名为letterFound(甚至letterFoundInWord2),因为这是您在双重循环中检查的内容。解释性命名使您更容易保持思想清晰。

由于您一次一次检查word1的一封信,因此您可以将letterFound的声明移入外部for循环中,并在此处将其初始化为false,因为每次您从word1中获取新的字母,您都没有找到它 word2。在for循环中的if语句中,如果字母相同,则break是正确的,并且将letterFound设置为true。在相反的情况下,不要打破,只需继续检查下一个字母即可。实际上,您可以完全删除else部分。

在内部for循环之后,如果letterFound仍然不是true,我们知道word1的字母不在word2中。因此stringCompare()应该返回false:

if (! letterFound) {
    return false;
}

随着此更改,在外部for循环之后,我们知道word1 的所有字母均在word2中找到,因此您可以在此处键入return true;

除外:

  • 您似乎假设字符串的长度相同。如果没有,您的程序将无法正常工作。
  • 正如安迪·特纳(Andy Turner)所说,您还应该检查word2中的所有字母是否在word1中;它不是从word1中的word2中的来信中遵循的。
  • 应该仅考虑字母?您是否应该忽略空间,数字,标点符号,…?

希望您能够弄清楚。随时在评论中跟进或提出新问题。

最新更新