How to keep the desired letter and hide the other characters with “*”? Is there a simpler and efficient way?

后端 未结 1 1146
独厮守ぢ
独厮守ぢ 2020-12-22 11:55

I want to keep the desired letter that the user inputs using the scanner and hide all the other characters with a \"*\", how would I do that with a for loop or substring? I

相关标签:
1条回答
  • 2020-12-22 12:26

    Try this updated version:

    String letters = "";
    for (int i = 0; i < 5; i++) {
        letters += keyboard.next().charAt(0) + ", ";
    }
    
    String r = "";
    boolean found = false;
    for (int y = 0; y < mysteryphrase.length(); y++) {
        char n = mysteryphrase.charAt(y);
        if (letters.indexOf(n) > -1) {
            r += n;
            found = true;
        } else {
            r += "*";
        }
    }
    if (!found) {
        System.out.println("Letters " + letters + " not in the word");
    } else {
        System.out.println(r);
    }
    

    Output for input a b c d e and mysteryphrase = "acknowledgement":

    ac*****ed*e*e**
    

    Output for input q b z r s and mysteryphrase = "acknowledgement":

    Letters q,b,z,r,s not in the word
    

    Or, if you have to do this task separately for each letter (not for all five ones together), you can extract a single method and call it 5 times:

    for (int i = 0; i < 5; i++) {
        char letter = keyboard.next().charAt(0);
        String r = "";
        boolean found = false;
        for (int j = 0, n = mysteryphrase.length(); j < n; j++) {
            char c = mysteryphrase.charAt(0);
            if (c == letter) {
                r += c;
                found = true;
            } else {
                r += '*';
            }
        }
        if (!found) {
            System.out.println("Letter " + letter + " not in the word");
        } else {
            System.out.println(r);
        }
    }
    

    Output:

    Letter b not in the word
    ******l*****
    a***********
    *c**********
    **k*********
    
    0 讨论(0)
提交回复
热议问题