它没有进入第一个循环,只打印“我只在循环外”。

huangapple go评论58阅读模式
英文:

It is not going inside the first loop and only printing I am outside loop only

问题

以下是您提供的代码的翻译部分:

package string_pattern;

public class Naive {

    public static void main(String[] args)
    {
        String pattern = "This is a text book";
        String text = "text";
        child obj = new child();
        obj.search(pattern, text);
    }
}

class child {
    public void search(String pat, String text)
    {
        int m, n;
        m = pat.length();
        n = text.length();
        System.out.println("我在循环外部");
        for (int i = 0; i <= (n - m); i++)
        {
            int j;
            System.out.println("我在第一个循环内部");
            for (j = 0; j < m; j++)
            {
                if (text.charAt(i + j) != pat.charAt(j))
                {
                    System.out.println("在这里");
                    break;
                }
                if (j == m)
                    System.out.println("在位置找到模式" + i);
            }
        }
    }
}

请注意,我已根据您的要求仅提供代码的翻译部分,去除了其他内容。如果您需要进一步的帮助,请随时询问。

英文:

The below code is not giving any error. After debugging i found it is not going inside the first loop.

 package string_pattern;

    public class Naive {
    
    	public static void main(String[] args)
    	{
    		String pattern=&quot;This is a text book&quot;;
    		String text=&quot;text&quot;;
    		child obj=new child();
    		obj.search(pattern, text);
    	}
    }

	
 class child{
	public void search(String pat,String text)
	{
		int m,n;
		m=pat.length();
		n=text.length();
		System.out.println(&quot;i am outside loop&quot;);
		for(int i=0; i&lt;= (n-m); i++)
		{
			int j;
			System.out.println(&quot;i am inside first loop&quot;); 
			for(j=0;j&lt;m;j++)
			{
				if(text.charAt(i+j) != pat.charAt(j))
				{
				System.out.println(&quot;OVER HERE&quot;);
					break;
				
				}
				if(j==m)
					System.out.println(&quot;pattern found at pos&quot; + i);
			}
		}
	}

}

答案1

得分: 1

你需要执行以下操作:

m = pat.length();
n = text.length();


问题在于`text`的长度为4,而`pat`较长。因此,当你像这样循环时 -&gt; `for(int i=0; i&lt;= (n-m); i++)`,你最终得到一个负数。因为0大于任何负数,所以你永远不会进入循环。
英文:

You do the following:

m=pat.length();
n=text.length();

The problem is that text has a length of 4, while pat is longer. So when you do the loop like this -> for(int i=0; i&lt;= (n-m); i++), you end up with a negative number. Since 0 is greater than any negative number you never enter the loop.

huangapple
  • 本文由 发表于 2020年9月5日 16:55:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63752144.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定