for 循环的字符替换方法的问题

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


有人能告诉我我做错了什么吗?谢谢!!


慕斯709654
浏览 111回答 2
2回答

Helenr

用遮罩后停止循环*for (int i = 0; i < major.length(); i++) {&nbsp; &nbsp; for (int j = 0; j < minor.length(); j++) {&nbsp; &nbsp; &nbsp; &nbsp; if (major.charAt(i) != minor.charAt(j)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; replace[i] = major.charAt(i);&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; replace[i] = '*';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break; // here&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.print(replace[i]);}System.out.print("\n");

万千封印

你永远不会打破你内在的循环。因此,您的 system.out.print(替换 [I]) 在将 e 从五个与来自 “五个手指” 的字母进行比较时,始终具有该值所以,每当你碰到我相信的其他东西时,你都会想要打破你内心的for-loop。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java