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

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

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

问题

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

  1. package string_pattern;
  2. public class Naive {
  3. public static void main(String[] args)
  4. {
  5. String pattern = "This is a text book";
  6. String text = "text";
  7. child obj = new child();
  8. obj.search(pattern, text);
  9. }
  10. }
  11. class child {
  12. public void search(String pat, String text)
  13. {
  14. int m, n;
  15. m = pat.length();
  16. n = text.length();
  17. System.out.println("我在循环外部");
  18. for (int i = 0; i <= (n - m); i++)
  19. {
  20. int j;
  21. System.out.println("我在第一个循环内部");
  22. for (j = 0; j < m; j++)
  23. {
  24. if (text.charAt(i + j) != pat.charAt(j))
  25. {
  26. System.out.println("在这里");
  27. break;
  28. }
  29. if (j == m)
  30. System.out.println("在位置找到模式" + i);
  31. }
  32. }
  33. }
  34. }

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

英文:

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

  1. package string_pattern;
  2. public class Naive {
  3. public static void main(String[] args)
  4. {
  5. String pattern=&quot;This is a text book&quot;;
  6. String text=&quot;text&quot;;
  7. child obj=new child();
  8. obj.search(pattern, text);
  9. }
  10. }
  11. class child{
  12. public void search(String pat,String text)
  13. {
  14. int m,n;
  15. m=pat.length();
  16. n=text.length();
  17. System.out.println(&quot;i am outside loop&quot;);
  18. for(int i=0; i&lt;= (n-m); i++)
  19. {
  20. int j;
  21. System.out.println(&quot;i am inside first loop&quot;);
  22. for(j=0;j&lt;m;j++)
  23. {
  24. if(text.charAt(i+j) != pat.charAt(j))
  25. {
  26. System.out.println(&quot;OVER HERE&quot;);
  27. break;
  28. }
  29. if(j==m)
  30. System.out.println(&quot;pattern found at pos&quot; + i);
  31. }
  32. }
  33. }
  34. }

答案1

得分: 1

  1. 你需要执行以下操作:

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

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

You do the following:

  1. m=pat.length();
  2. 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:

确定