-
April 24th, 2015, 11:21 AM
#1
Reading text from hangman file in Java
I was wanting to know if my code was done correctly? The code has to read text from the hangman file. I compiled the code and I did not get any syntax errors, but I want to make sure everything is correct.
Code:
public static void main(String[] args)throws Exception{
java.io.File file = new java.io.File("c:\\hangman.txt");
String[] words = {"write", "program", "that", "receive", "positive","red","battery","jeans",
"soda", "chips", "pizza", "cable"};
char anotherGame;
Scanner fileInput = new Scanner(new File("c:\\hangman.txt"));
int count = 0;
while (fileInput.hasNext()) {
fileInput.next();
count++;
}
fileInput.close();
Scanner input = new Scanner(System.in);
do {
int index = (int)(Math.random() * words.length);
String hiddenWord = words[index];
StringBuilder guessedWord = new StringBuilder();
for (int i = 0; i < hiddenWord.length(); i++) {
guessedWord.append('*');
}
int numberOfCorrectLettersGuessed = 0; int numberOfMisses = 0;
while (numberOfCorrectLettersGuessed < hiddenWord.length()) {
System.out.print("(Guess) Enter a letter in word " + guessedWord +
" > ");
String s = input.nextLine();
char letter = s.charAt(0);
if (guessedWord.toString().indexOf(letter) >= 0) {
System.out.println("\t" + letter + " is already in the word");
} else if (hiddenWord.indexOf(letter) < 0) {
System.out.println("\t" + letter + " is not in the word");
numberOfMisses++;
} else {
int k = hiddenWord.indexOf(letter);
while (k >= 0) {
guessedWord.setCharAt(k, letter);
numberOfCorrectLettersGuessed++;
k = hiddenWord.indexOf(letter, k + 1);
}
}
}
System.out.println("The word is " + hiddenWord + ". You missed " + numberOfMisses
+ (numberOfMisses <= 1 ? " time" : " times"));
System.out.print("Do you want to guess for another word? Enter y or n> ");
anotherGame = input.nextLine().charAt(0);
}while (anotherGame == 'y');
}
}
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|