我正在尝试制作一个比较两个字符串并用星号替换并发字符的方法,以供初学者练习。我认为在String类或其他类中已经存在一些方法来做到这一点,但该练习不允许我使用它们。我试图用for循环来做到这一点。这是我的代码:public void substrings(){ System.out.println ("Insert string 1 and press Intro"); String string1 = sc.nextLine(); System.out.println ("Insert string 2 and press Intro"); String string2 = sc.nextLine(); String major; String minor; if (string1.length() >= string2.length()){ major = string1; minor = string2; } else{ major = string2; minor = string1; } char[]replace = new char[major.length()]; for (int i = 0; i < major.length(); i++){ for (int j = 0; j < minor.length(); j++){ if (major.charAt(i) != minor.charAt(j)){ replace[i] = major.charAt(i); } else { replace[i] = '*'; } } System.out.print (replace[i]); } System.out.print ("\n");}public static void main (String[]args){ Substrings Test = new Substrings(); Test.substrings();}}如果我插入字符串1,并插入字符串2,我得到这些:five fingersfivefiv* fing*rs虽然我期待一些喜欢**** **ng*rs有人能告诉我我做错了什么吗?谢谢!!
2 回答

Helenr
TA贡献1780条经验 获得超4个赞
用遮罩后停止循环*
for (int i = 0; i < major.length(); i++) {
for (int j = 0; j < minor.length(); j++) {
if (major.charAt(i) != minor.charAt(j)) {
replace[i] = major.charAt(i);
} else {
replace[i] = '*';
break; // here
}
}
System.out.print(replace[i]);
}
System.out.print("\n");

万千封印
TA贡献1891条经验 获得超3个赞
你永远不会打破你内在的循环。因此,您的 system.out.print(替换 [I]) 在将 e 从五个与来自 “五个手指” 的字母进行比较时,始终具有该值
所以,每当你碰到我相信的其他东西时,你都会想要打破你内心的for-loop。
添加回答
举报
0/150
提交
取消