我目前在计算机编程课上,并为这个2人挂人游戏的“创建模板”而死路一条。如何根据另一个字符串的未知长度创建一个新的字符串?
- 首先,人#1提示短语(包含全部小写)
- 然后,我一定要把他们选择的任何短语,并与所有把它变成一个模板?的。
- 然后,当人#2猜出字母时,我必须“揭示”这个短语,并把这个短语变成短语字母。
虽然我无法将它转换成模板。一个例子是:
人#1的一句话:“世界你好”
所需的模板的结果:“??????????”
这是我在公共静态字符串createTemplate那么远,我有麻烦(字符串sPhrase)
import java.util.Scanner;
public class Program9
{
public static void main (String[] args)
{
Scanner scanner = new Scanner (System.in);
Scanner stdIn = new Scanner (System.in);
int cnt = 0; //counter is set to zero
String sPhrase;
boolean def;
System.out.print("Enter a phrase consisting of only lowercase letters and spaces: ");
sPhrase = scanner.nextLine(); //reads into variable set to Scanner.nextLine()
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String template = createTemplate(sPhrase); //will run through "createTemplate" and show whatever on there.
do
{
char guess = getGuess(stdIn); //will run through "getGuess" and show whatever SOP and return from that. WORKS.
cnt = cnt + 1; //counts the guess
System.out.println("\n\n\nCommon Phrase");
System.out.println("--------------\n");
String updated = updateTemplate(template, sPhrase, guess); //runs throuhgh and prints updated template
} while (!exposedTemplate(sPhrase)); //will loop back if updated template still has ?'s
System.out.println("Good job! It took you " + cnt + " guesses!");
}
public static String createTemplate(String sPhrase)
{
String template = null;
String str;
sPhrase.substring(0, sPhrase.length()+1); //not sure if +1 needed.
sPhrase.equals(template);
//THIS IS WHERE IM HAVING PROBLEMS
}
public static char getGuess(Scanner stdIn)
{
//repeatedly prompts user for char response in range of 'a' to 'z'
String guess;
do
{
System.out.print("Enter a lowercase letter guess : ");
guess = stdIn.next();
} while (Character.isDigit(guess.charAt(0)));
char firstLetter = guess.charAt(0);
return firstLetter;
}
public static String changeCharAt(String str, int ind, char newChar)
{
return str.substring(0, ind) + newChar + str.substring(ind+1);
//freebie: returns copy of str with chars replaced
}
public static String updateTemplate(String template, String sPhrase, char guess)
{
//will have to include changeCharAt
}
public static boolean exposedTemplate(String template)
{
// returns true exactly when there are no more ?'s
}
}
的'.'取而代之的是几乎从来没有一个好主意。在这种情况下,您将用问号替换原文中的空格和连字符,即。 “ANNA-MAE”将变成“????????”这对于只有字母可以被猜测的hang子手游戏来说是不正确的。 – 2014-11-24 03:27:08
很容易改变正则表达式只挑选字符,或任何匹配你想..我说的“。”匹配所有的字符,只是将其更改为[a-zA-Z]或其他任何... – CharlieS 2014-11-24 03:29:35
是的,但正如目前所写,此解决方案不适用于问题中发布的“hello world”示例。 – 2014-11-24 03:31:13