英文:
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="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("i am outside loop");
		for(int i=0; i<= (n-m); i++)
		{
			int j;
			System.out.println("i am inside first loop"); 
			for(j=0;j<m;j++)
			{
				if(text.charAt(i+j) != pat.charAt(j))
				{
				System.out.println("OVER HERE");
					break;
				
				}
				if(j==m)
					System.out.println("pattern found at pos" + i);
			}
		}
	}
}
答案1
得分: 1
你需要执行以下操作:
m = pat.length();
n = text.length();
问题在于`text`的长度为4,而`pat`较长。因此,当你像这样循环时 -> `for(int i=0; i<= (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<= (n-m); i++), you end up with a negative number. Since 0 is greater than any negative number you never enter the loop.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论