2014-09-04 51 views
0

我在java中有一个hangman任务,除了当它试图读取输入并保存它时,我的大部分程序都可以工作。因为我不想惹我只用串字符转换为字符串hangman输入不会被读取

我主:

public static void main(String[] args) 
{ 
    Scanner input = new Scanner(System.in); 

    boolean active = true; 
    do 
    { 
     startGame(); 
     do 
     { 
      System.out.println("You have "+(numGuesses)+" guesses left"); 
      drawBoard(); 

      System.out.println(); 
      System.out.println("Please enter your next guess: "); 
      String mainGuess = input.nextLine(); 
      if ("stop".equals(mainGuess)) 
       currentState = End;//stops game if player chooses 
      else 
      { 
       wordCondition(mainGuess); 
       winLose(); 
      } 
     } 
     while (currentState == Play); 

     if (currentState == Win) 
      System.out.println("Coongradulations you won!"); 
     else if (currentState == Lose) 
      System.out.println("Sorry, You lost"); 

     System.out.println("Would you like to play again? 1)yes 2)no"); 
     int answer=input.nextInt(); 
     active = (answer==1); 
    } 
    while (active);//creates a new game as much as user wants 
} 

和我的问题块

public static void wordCondition(String guess) 
{ 
    if (guess.contains(word))//check if letter is in word and substitutes the letter 
    { 
     board[guess.indexOf(word)]=guess; 
     total++; 
    } 

和我的画块

public static void drawBoard() 
{ 
    System.out.println("Current word:"); 
    for(int i=0;i<word.length();i++) 
     System.out.print(board[i]); 
} 

例如,单词是“nam E” 我想要什么

你7个猜测留下 当前词:_ _ _ _ 请输入你的下一个猜测: 一个

您有7个猜测留下 当前词:_一_ 请输入你的下一个猜测:

我得到什么

你7个猜测留下 目前的一句话:_ _ _ _ 请输入你的下一个猜测: 一个

您已经6个猜测留下 当前词:_ _ _ _ 请输入你的下一个猜测:

或类似的东西,格式是有点关 请帮助:)

+6

时间倾向于如何使用IDE的调试器。 – OldProgrammer 2014-09-04 13:11:16

+0

你的“问题块”产生了什么问题? – APerson 2014-09-04 13:12:11

+0

在哪里以及如何定义“board”? – m0skit0 2014-09-04 13:15:38

回答

3

这只是一个疯狂的猜测,但不是代码错误?

public static void wordCondition(String guess) 
{ 
    //check if letter is in word and substitutes the letter 
    if (guess.contains(word)) 
     board[guess.indexOf(word)]=guess; 
    else 
     numGuesses--; 
} 

您正在检查输入字母是否包含单词。你应该检查周围用另一种方式:

public static void wordCondition(String guess) 
{ 
    //check if letter is in word and substitutes the letter 
    if (word.contains(guess)) 
     board[word.indexOf(guess)]=guess; 
    else 
     numGuesses--; 
} 

但是,这将取代只有一个字母 - 如果将有两个a那么只有一个会被取代。你应该想一些其他方式来做到这一点。

扰流

你可以使用这个来代替所有的字母。但是你应该真的使用char []并且改变你的方法:

public static void wordCondition(String guess) 
{ 
    int position = 0; 
    boolean found = false; 
    for (char letter : word.toCharArray()) 
    { 
     if (letter == guess.toCharArray()[0]) 
     { 
      board[position]=guess; 
     } 
     position++; 
    } 

    if (!found) 
    { 
     numGuesses--; 
    } 
} 
+1

Ejaaaaaaaaaaaaaaaaaactly,我的想法,关于主题:-) +1 – 2014-09-04 13:16:40

+1

@nIcEcOw - 我们在同一时间发布它 - 我去的答案,而不是评论(虽然有一些疑惑)) – 2014-09-04 13:22:19

+0

ive试过,但它不断回来作为错误 – 2014-09-04 13:24:39