2016-09-28 75 views
1

我被要求創建hang子手遊戲。我有問題。當我詢問用戶是否想再次玩時,用戶將輸入Y,但遊戲不會重新啓動正確的方式,因爲它不會選擇一個新單詞,只是繼續詢問該字母,並在該字母輸入時停止遊戲並詢問用戶他是否想再玩一次。有人可以告訴我如何循環我的程序,以便用戶可以再次玩遊戲。包裹hang子手 。Hang子手循環問題

public static void main(String args[]) throws IOException { 

    Scanner keyboard = new Scanner(System.in); 
    int random = (int) (Math.random() * 5); 
    String s = null; 
    InputStream input = null; 
    int play = 0; 
    Path file = Paths.get("H:\\Varsity work\\Java       
     Programming\\Programs\\HangMan\\src\\hangman\\HangMan.txt"); 
     input = Files.newInputStream(file); 
     BufferedReader reader = new BufferedReader(new              InputStreamReader(input)); 
     ArrayList<String> lines = new ArrayList<String>(); 
     while ((s = reader.readLine()) != null) { 
      lines.add(s); 
     } 
     String[] linesArray = lines.toArray(new String[lines.size()]); 
     String[] randomWord = new String[1]; 
     while (play == 0) { 
      System.err.printf("Welcome to hangman.\n"); 
      randomWord[0] = linesArray[random]; 
      System.out.println(randomWord[0]); 
      Random ran = new Random(); 
      String word = randomWord[ran.nextInt(randomWord.length)]; 
      char[] CharArr = word.toCharArray(); 
      char[] dash = word.toCharArray(); 
       for (int i = 0; i < dash.length; i++) { 
        dash[i] = '-'; 
        System.out.print(dash[i]); 
       } 
      for (int i = 1; i <= dash.length; i++) { 
       System.out.printf("\nGuess a Letter:"); 
       char userLetter = keyboard.next().charAt(0); 

       for (int j = 0; j < CharArr.length; j++) { 
        if (userLetter == dash[j]) { 
         System.out.println("this word already exist"); 
        } else if (userLetter == CharArr[j]) { 
         dash[j] = userLetter; 
         i--; 
        } 
       } 
       System.out.print(dash); 
       if (word.equals(new String(dash))) { 
        System.out.println("\nYou have guessed the word correctly!"); 
        System.out.println("Play adian? (y/n)"); 
        String name = keyboard.next(); 
        if(name.equals("y")) { 
         play = 0; 
        } else if(name.equals("n")) { 
         play = 1; 
         return; 
        } 
       }     
      }  
     } 
    } 
+0

請打算你的代碼,它是可怕的閱讀。 – SomeJavaGuy

+0

使用'infite'循環與'布爾值' – 2016-09-28 10:42:11

+0

@HelloWorld它似乎工作 –

回答

2

隨着你目前的邏輯,這是不可能的,因爲你的代碼是混亂的。你必須將代碼分解成方法。我會把它分成以下幾種方法:

setUpGame(); 
game(); 
cleanUpAfterGame(); 

setUpGame() { 
    chooseWord(); 
    paintBasicHangman(); 
} 

game() { 
    while (alive) { 
     readLetterFromUser(); 
     if (missedLetter) { 
      paintNextPartOfHangman(); 
     } else { 
      redraw(); 
      if (won()) { 
       return true; 
      } 
     } 
    } 
    return false; 
} 

controller() { 
    do { 
     setUpGame(); 
     game(); 
     cleanUpAfterTheGame(); //optional 
     wantsNewGame?(); 
    } while (userWantsToPlay)