据我所知(和理解),您面临的基本问题是由for
比较方法中的循环引起的。
(注意,我的示例区分大小写,您需要考虑到这一点)
我可以建议两种基本方法...
第一个是,通过一次检查匹配所有出现...
private char guessCh;
private String secretWord;
private String status;
private String secretBuffer;
public TestStringCompare() {
secretWord = "This is a test";
// This is a copy of the secret word, this ensures that
// we always have a copy of the original.
secretBuffer = secretWord;
status = "______________";
guessCh = 'i';
compare("i");
}
private void compare(String str) {
while (secretBuffer.contains(str)) {
int foundAt = secretBuffer.indexOf(str);
status(str.charAt(0), foundAt);
// We want to remove the "guess" from our check string
// so it doesn't cause a false positive in the future
StringBuilder sb = new StringBuilder(secretBuffer);
sb.replace(foundAt, foundAt + 1, "_");
secretBuffer = sb.toString();
System.out.println(secretBuffer);
}
}
private String status(char guessCh, int placement) {
/* Update and return status. */
if (Character.isLetter(guessCh)) {
status = new StringBuffer(status).deleteCharAt(placement).toString();
status = new StringBuffer(status).insert(placement, guessCh).toString();
System.out.println("That guess is correct.");
System.out.println(status);
}
return status;
}
这会产生:
That guess is correct.
__i___________
Th_s is a test
That guess is correct.
__i__i________
Th_s _s a test
或者,替换第一次出现的猜测(据我所知,这是你所追求的)
public class TestStringCompare {
public static void main(String[] args) {
new TestStringCompare();
}
private char guessCh;
private String secretWord;
private String status;
private String secretBuffer;
public TestStringCompare() {
secretWord = "This is a test";
secretBuffer = secretWord;
status = "______________";
guessCh = 'i';
compare("i");
}
private void compare(String str) {
if (secretBuffer.contains(str)) {
int foundAt = secretBuffer.indexOf(str);
status(str.charAt(0), foundAt);
// Some where here you need to remove the "guess" character
// to ensure that it doesn't get repeated...
StringBuilder sb = new StringBuilder(secretBuffer);
sb.replace(foundAt, foundAt + 1, "_");
secretBuffer = sb.toString();
System.out.println(secretBuffer);
}
}
private String status(char guessCh, int placement) {
/* Update and return status. */
if (Character.isLetter(guessCh)) {
status = new StringBuffer(status).deleteCharAt(placement).toString();
status = new StringBuffer(status).insert(placement, guessCh).toString();
System.out.println("That guess is correct.");
System.out.println(status);
}
return status;
}
}
哪个会产生这个...
That guess is correct.
__i___________
Th_s is a test