Java中twoOccurences方法内第二个System.out.println()未执行问题咨询
问题出在第一个条件判断写反啦!
兄弟,你这段代码的核心问题就是第一个if-else的逻辑完全搞反了,导致包含第二个System.out.println()的else块根本没机会执行,自然看不到它的输出,而且所有测试用例都返回false。
具体原因拆解
看这段关键代码:
if(b.indexOf(a)!=-1){ return false; }else{ System.out.println(index); // 统计次数的循环逻辑 }
b.indexOf(a)!=-1代表的是stringa在stringb里找到了匹配项,但你这时候直接返回false,程序直接跳出方法,后面的else代码块连执行的机会都没有!
举个例子,第一个测试用例twoOccurences("by", "A story by Abby Long"),b.indexOf("by")会返回7(有效索引,说明找到匹配),满足!=-1的条件,直接返回false,else里的代码一行都没跑,第二个System.out.println当然不会输出。
修复代码
把第一个条件反过来,改成找不到匹配才返回false,找到的话再进入统计次数的逻辑:
public class Part3 { public static boolean twoOccurences(String stringa,String stringb){ String a=stringa; String b=stringb; int index=0,count=0; System.out.println(index); // 修正条件:找不到匹配才返回false if(b.indexOf(a) == -1){ return false; }else{ System.out.println(index); while(index!=-1){ index=b.indexOf(a,index); if(index!=-1){ count++; index=index+a.length(); } } } boolean result = count>=2; System.out.println(result); return result; // 简化return语句,更简洁 } public static void main(String args[]){ System.out.println(twoOccurences("by", "A story by Abby Long")); System.out.println(twoOccurences("a", "banana")); System.out.println(twoOccurences("atg", "ctgtatgta")); } }
修复后的运行结果
修改后执行main方法,输出会变成:
0 0 true true 0 0 true true 0 0 false false
可以看到第二个System.out.println()正常输出了,而且返回结果也符合预期:
- "by"在目标字符串中出现2次,返回true
- "a"在"banana"中出现3次,返回true
- "atg"在目标字符串中仅出现1次,返回false
内容的提问来源于stack exchange,提问作者usr123
相关产品推荐
相关产品推荐

