我正在为我的作业写一个hang子手程序,并遇到一个小问题。 在我的程序中,为了分开单词,我使用'|'符号。 例如这是这个词来猜测:如何在单词之间添加分隔符?
U N I T E D | S T A T E S | O F | A M E R I C A
我有显示没有一个StringBuffer变量。破折号 这里,
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
我试着用下面的代码插入分隔符“|”
if(guessword.indexOf('|') == -1)
System.out.print(" ");
else
guessit.setCharAt(guessword.indexOf('|'),'|');
我知道它错了,它只插入1个分隔符。 你能帮我把分离器插在正确的位置吗? 也可以尝试删除System.out.print(“”);因为它不必要地留下空间。 我可以使用break吗?而不是 对于上述例如我得到的显示器作为
_ _ _ _ _ _ | _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
其实我是想
_ _ _ _ _ _ | _ _ _ _ _ _ | _ _ | _ _ _ _ _ _ _
我的主要方法如下
public static void main()throws IOException
{
Hangman obj = new Hangman();
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
PrintWriter p = new PrintWriter(System.out,true);
p.println("Lets play HANGMAN");
p.println();
p.println("Enter your choice according to the following options.\n
NOTE: Words are related to the topics given below.\n
1. Sports\n2. Movies\n3. Computer\n4. Food\n5. Countries");
p.println();
int choice = Integer.parseInt(br.readLine());
obj.clearScreen();
String bothwordandclue[] = new String[2];
if(choice == 1)
bothwordandclue = obj.Sports();
else if(choice == 2)
bothwordandclue = obj.Movies();
else if(choice == 3)
bothwordandclue = obj.Computers();
else if(choice == 4)
bothwordandclue = obj.Food();
else if(choice == 5)
bothwordandclue = obj.Countries();
else
p.println("Wrong choice");
int counter = 6;
String guessword = bothwordandclue[0];
String wordclue = bothwordandclue[1];
int lengthofword = (int)(Math.round(((double)guessword.length()/2)));
int checkguess = 0;
String a;
StringBuffer guessit = new StringBuffer();
for (int i = 0;i < lengthofword; i++)
guessit = guessit.append("_ ");
guessit.delete((2 * lengthofword)-1,(2 * lengthofword));
if(guessword.indexOf('|') == -1)
System.out.print(" ");
else
guessit.setCharAt(guessword.indexOf('|'),'|');
p.println(guessit);
do
{
p.println();
p.println("Enter your guess letter in capitals");
String guessletter = br.readLine();
obj.clearScreen();
for(int i = 0;i<lengthofword;i++)
{
if(guessletter.charAt(0) == guessword.charAt(2*i))
{
guessit.setCharAt(2*i,guessletter.charAt(0));
checkguess=1;
}
}
if(checkguess == 1)
{
p.println("Correct Guess");
p.println(guessit);
}
else
{
counter--;
p.println("Wrong guess. You have " + counter +
" incorrect guesses left");
p.println(guessit);
}
checkguess = 0;
a = guessit.toString();
if(a.equals(guessword))
{
p.println("You guessed the word!!!!!");
counter=0;
}
}while(counter>0);
}
Upvote因为它比我的更有效地解决了问题,但对于初学者来说并不明显。也许包含http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String的链接。html#indexOf(java.lang.String,int) –
@Phhite。当然:) –
非常感谢。这非常有效地解决了问题。 – crvineeth99