2017-05-08 1 views
1

이 프로그램은 .txt 파일에서 임의의 단어를 선택하고 사용자가 단어에 대한 문자를 추측 해보라고합니다. 그것은 실행되지만, 모든 단어에있는 편지라는 것을 알고있을 때에도 항상 "단어는 발견되지 않았습니다"라고 말합니다. 이것은 내가 .txt 파일을 제대로 읽지 못한다고 생각하게 만듭니다.행맨 게임에서 파일을 읽을 수 없음

package hangman; 

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Arrays; 
import java.util.Random; 
import java.util.Scanner; 
public class Hangman{ 



public static void main(String[] args) { 

    ArrayList<String> dictionaryList = new ArrayList<>(); 
    File file = new File("src/hangman.txt"); 
     try { 
     try (Scanner scanner = new Scanner(file)) { 
      while (scanner.hasNextLine()) { 
       String line = scanner.nextLine(); 
       dictionaryList.add(line); 
      } 
     } 
     } catch (FileNotFoundException e) { 
     } 

     /* 
     * Getting the word and hiding it 
     */ 

     Random rng = new Random(); 
     int word = rng.nextInt(dictionaryList.size()); //randomly chooses a word from the text file 
     Scanner scanner = new Scanner(System.in); 
     int guessesLeft = 6; // the total amount of guesses the user gets 
     ArrayList<Character> alreadyGuess = new ArrayList<>(); // keep tracks of the user's guesses 
     boolean wordFound = false; // keeps track of when the game will end after the user runs out of guesses 


     String wordSelected = dictionaryList.get(word); //converts the int value of the randomly choose word to a string 
     char[] letters = wordSelected.toCharArray(); // converts the word to a char 
     char[] hideWord = new char[letters.length]; // gets the length of hiding the word 


     // the for loop hides the word by replacing it with '_' 
     for(int i = 0; i < letters.length; i++) { 
      hideWord[i]='_'; 
     } 

     /* 
     * Starts the hangman game. The while loop will keep running the game. 
     */ 

     while(true){ 

      //for testing purposes they can use the print statement below to replace the other print statement 
      //System.out.print("\n" + wordSelected + "\n" + "Word: "); 
      System.out.print("\n" + "Word: "); 
      for(int i = 0; i < letters.length; i++){ 
       System.out.print(hideWord[i]); 
      } // Display the word 

      // Allows user to input and displays the guesses that are left 
      System.out.print("\n" + "Guesses Left: " + guessesLeft +"\nAlready Guess: " + alreadyGuess + "\nGuess: "); 
      char userInput = scanner.nextLine().toUpperCase().charAt(0); // uppercase the String first, and then pick the char 

      // Checks to see if the user already guess the same word 
      for(int i = 0; i < alreadyGuess.size(); i++){ 
       if(userInput==alreadyGuess.get(i)){ 
        System.out.println("\nYou already guessed this letter. Try Again. "); 
        break; 
       } 
      } 

      // records the user's guesses 
      if(!(alreadyGuess.contains(userInput))){ 
       alreadyGuess.add(userInput); 
      } 


      // Checks if the user guesses the right letter in the word 
      for(int i = 0; i < letters.length; i++) { 
       if(userInput==letters[i]) { 
        hideWord[i] = userInput; 
        wordFound = true; 

       } 
      } 


     // If user guesses the incorrect letter it will display this and lower the amount of guesses 
     if(!wordFound){ 
      System.out.println("\nThe letter was not found in the word. \n"); 
      guessesLeft = 1; 
     } 


     wordFound = false; // resets the wordFound boolean back to false 

     // if user runs out of guesses left, they will lose. 
     if(guessesLeft<=0){ 
      System.out.println("\nYou lose, you hanged the man."); 
      break; 
     } 

     // if user guesses correctly on the word, they win. Uses the array class to compare two char arrays 
     if(Arrays.equals(letters,hideWord)){ 
      System.out.println("\nWord: " + wordSelected); 
      System.out.println("\nCongratulations! You guess the right word and save the man from being hang."); 
      break; 
     } 


} 
    } 
} 
+5

당신이 선택한 단어를 인쇄하여 가설을 테스트 할 수 있습니다. 단어가 잘 보이는 경우 문제는 텍스트 파일을 읽는 것과 아무런 관련이 없습니다. 단어가 제대로 보이지 않으면 텍스트 파일을 읽는 코드 나 임의로 선택하는 코드가 잘못되었습니다. 그러나 실제로, 우리는 많은 코드를 던지고 우리가 작업을 수행하기보다는 스스로 코드를 직접 디버깅해야합니다. 이것은 당신의 임무가 아니라 우리의 임무가되어야합니다. – ajb

답변

0

결코 예외를 포착하고 예외를 무시하지 마십시오! 이 같은 프로그램의 상단에있는 캐치 절을 변경 :

catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} 

을 그래서 당신은 당신의 단어 목록을 읽는 동안 나쁜 일이 일어난 경우 적어도 힌트를 가질 것이다.

이것은 굵은 글씨로 반복되는 중요한 교훈입니다. 결코 예외를 포착하고 무시하지 마십시오!

관련 문제