以下程序在“else”部分有问题

时间:2016-06-23 19:00:16

标签: java arrays

只有在整个组合中没有subString匹配时才会出现“else”部分,或者只有在找不到匹配项时才能使用“else”部分。

代码:

public class Stringg {

    public static void main(String[] args)

    {
        char[] array1 ={'a','c','t','i','a','n','c','e'};
        String Str2 ="cti";

        for (int i = 0; i < array1.length-Str2.length(); i++) 
        {
            String Str ="";
            for (int j = i; j < i+ Str2.length(); j++) 
            {

                Str+=array1[j];

            }

            if(Str.equalsIgnoreCase(Str2))
            {
                System.out.println("This is a substring");
                break;
            }
            else{
                System.out.println("This is not a substring");
            }

        }

    }

}

输出:

This is not a substring

This is a substring

3 个答案:

答案 0 :(得分:1)

在for循环后移动System.out.println("This is not a substring)并将return替换为break。这样,如果方法是子字符串,该方法将退出。如果它不会退出,只有当整个组合不匹配时,才会打印This is not a substring

最终结果将如下所示:

class Stringg {
    public static void main(String[] args)

    {
        char[] array1 = {'a', 'c', 't', 'i', 'a', 'n', 'c', 'e'};
        String Str2 = "cti";

        for (int i = 0; i < array1.length; i++) {
            String Str = "";
            for (int j = i; j < i + Str2.length(); j++)
                Str += array1[j];

            if (Str.equalsIgnoreCase(Str2)) {
                System.out.println("This is a substring");
                return;
            }

        }
        System.out.println("This is not a substring");
    }

}

它的工作原理如下:

  1. 检查是否匹配
  2. 如果有打印This is a substring并退出方法,则重复第1步
  3. 如果没有任何组合成功打印This is not a substring

答案 1 :(得分:1)

您可以在主for循环之前创建boolean isSubstring = false,然后如果有匹配的子字符串,则设置isSubstring = true。然后,一旦整个循环结束,只需要一个if语句,如:

if(isSubtring == false) { System.out.println("This is not a substring"); }

答案 2 :(得分:0)

也许这样

    public class Stringg {

    public static void main(String[] args) {

        int matchingCount = 0;

        char[] array1 = {'a', 'c', 't', 'i', 'a', 'n', 'c', 'e'};
        String Str2 = "cti";

        for (int i = 0; i < array1.length - Str2.length(); i++) {
            String Str = "";
            for (int j = i; j < i + Str2.length(); j++) {

                Str += array1[j];
            }

            if (Str.equalsIgnoreCase(Str2)) {
                matchingCount++;
                System.out.println("This is a substring");
                break;
            }
        }

        if (matchingCount < 1) {
            System.out.println("This is not a substring");
        }
    }
}

输出:

This is not a substring