Java Beginner,比较嵌套for循环中的字符串

时间:2017-02-17 19:24:37

标签: java loops anagram

这是问题陈述:编写一个比较2个字符串的函数,返回true或false,具体取决于两个字符串是否包含相同的字母。订单并不重要。

我不知道如何正确比较嵌套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...");
    }

}

3 个答案:

答案 0 :(得分:1)

以下代码将完成这项工作。这基本上是弗兰克上述评论的扩展。我们将两个字符串转换为两个字符串然后进行比较。

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

}

答案 1 :(得分:1)

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

    //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();
    }
    }

答案 2 :(得分:0)

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

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

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

if (! letterFound) {
    return false;
}

通过此更改,在外部for循环后,我们知道word1 中的所有字母都是<{1}}中的,因此您可以输入{{1这里。

除了:

  • 您似乎假设字符串具有相同的长度。如果他们没有,你的程序将无法正常工作。
  • 正如Andy Turner所说,您还应检查word2中的所有字母是否都在return true;;它不会来自word2word1的{​​{1}}字母。
  • 是否只应考虑字母?你应该忽略空格,数字,标点符号......?

希望你能弄明白。随意在评论中跟进或提出新问题。

相关问题