0

I am a newbie to Java and would be very grateful if someone could look into this code snippet and give me a hand.

@SuppressWarnings("unused")
public static void main(String[] args) throws IOException {

    File fin = new File("wordList");
    FileInputStream fis = new FileInputStream(fin);
    BufferedReader br = new BufferedReader(new nputStreamReader(fis));
    List<String> wordList = new ArrayList<>(); 
    List<Character> guessedCharacters = new ArrayList<>();
    char guessedCharacter;

    String line = "";
    while ((line = br.readLine()) != null) {
        wordList.add(line);
    }
    br.close();

    System.out.println("Welcome to hanged man.");
    System.out.println();

    for (int i = 0; i < wordList.size(); i++) {

        System.out.print("Guess a letter: ");
        guessedCharacter = (char) System.in.read();
        System.out.println('\n');

    }

When I run the code snippet above I get the following output:

Welcome to hanged man.

Guess a letter: d

Guess a letter:

Guess a letter:

My intention is to have the prompt "Guess a letter" appear only once after I enter the first letter.

If I replace "wordList.size()" in the for-loop with any integer larger than three I get the same result.

I hope to hear from someone. Thank you in advance. Marcos

Héctor
  • 19,875
  • 26
  • 98
  • 200
  • 1
    Please post a sample _wordList_ file, and the expected output . – Arnaud Apr 04 '16 at 13:56
  • It is not clear what you want to do. Do you want the user to guess all the words in your wordList? There is nothing in your code that checks the guessedCharacter. Do you want to display only once "Guess a letter:" for a given word to guess or for all words to guess? – Nicolas Filotto Apr 04 '16 at 14:18

2 Answers2

1

What you are looking for is either using the Scanner class (probably not, as your exercise looks trivial and you probably just want the easiest way to read keyboard inputs without any GUI) or, most probably, this :

String answer = System.console().readLine("Guess a letter : ");

Don't use System.read() to read keystrokes (or unless you want to complicate things "just for the fun" :)

niilzon
  • 436
  • 2
  • 17
  • Hello. I resolved the little issue by using the class Scanner. I just wonder why it did not work using the method read() of System.in – user2143292 Apr 04 '16 at 18:21
  • In any case, I will stick to the latest additions made to Java. Thank you kindly for responding to my question. – user2143292 Apr 04 '16 at 18:23
0

With System.read.in() you read 'd' and '\n' values. Try to use Scanner class (see here)

Community
  • 1
  • 1
borras
  • 116
  • 2
  • 12