【问题标题】:Issue with a character substitution method by for-loopfor循环的字符替换方法问题
【发布时间】:2019-04-10 16:32:03
【问题描述】:

我正在尝试制作一种方法来比较两个字符串并用星号替换并发字符以供初学者练习。 我想在 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();


}}

如果我将 five fingers 作为字符串 1 插入,并将 five 作为字符串 2 插入,我会得到这些: fiv* fing*rs

虽然我期待像**** **ng*rs这样的人

谁能告诉我我做错了什么?谢谢!!

【问题讨论】:

  • 在 Java 8 中更容易:string1.chars().mapToObj(e -&gt; String.valueOf((char) (string2.chars().anyMatch(e2 -&gt; e == e2) ? '*' : e) )).forEach(System.out::print);

标签: java string for-loop


【解决方案1】:

使用* 屏蔽后停止循环

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");

【讨论】:

    【解决方案2】:

    你永远不会跳出你的内部 for 循环。所以你的 system.out.print(replace[I]) 在比较 e 来自 5 和 'five finger' 的字母时总是有值

    所以当你点击 else 语句时,我相信你会想要打破你的内部 for 循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-14
      • 2017-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 2022-01-14
      • 2011-09-22
      相关资源
      最近更新 更多